Convert Date Value to Specific Format in C#

22,729

Solution 1

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));

Solution 2

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");
Share:
22,729
Suave Nti
Author by

Suave Nti

.....................................

Updated on July 06, 2022

Comments

  • Suave Nti
    Suave Nti almost 2 years

    How to convert any date format to a specified format in C#.

    For example:

    If Date Format is

    14.11.2011 or 14/11/2011 
    

    Looking for a conversion function which converts into

    yyyy-MM-dd format like 2011-11-14
    
  • Andrew Barber
    Andrew Barber over 12 years
    Correct; The question is also asking about parsing, though. Or at least it seems logical to assume that, since it talks about an existing date format (which does not apply if you already have a DateTime object.)
  • Suave Nti
    Suave Nti over 12 years
    Thanks Andrew, Appreciate your kind time to anwser rather than downvoting :)
  • Andrew Barber
    Andrew Barber over 12 years
    @DarkRider You are welcome. However, three things: 1) Don't make assumptions about who voted up/down based on comments/answers. It's very possible I did down vote, and abatishchev did not. 2) Don't take down votes personally. 3) You could, possibly, have found an answer more quickly by searching. (although in this specific case, you did get a few answers very fast...)
  • Suave Nti
    Suave Nti over 12 years
    Thanks andrew, But times downvote will discourage a fresher to ask a question in SO. such in my case :)
  • Andrew Barber
    Andrew Barber over 12 years
    @DarkRider You are exactly right in a way: Down votes discourage the questions that get down voted. That is exactly intended. I've been down voted plenty of times; I learn from it.