Search code examples
c#.netstringparsingdatetime

How to parse strings to DateTime in C# properly?


I have date and time in a string formatted like that one:

"2011-03-21 13:26" //year-month-day hour:minute

How can I parse it to System.DateTime?

I want to use functions like DateTime.Parse() or DateTime.ParseExact() if possible, to be able to specify the format of the date manually.


Solution

  • DateTime.Parse() will try figure out the format of the given date, and it usually does a good job. If you can guarantee dates will always be in a given format then you can use ParseExact():

    string s = "2011-03-21 13:26";
    
    DateTime dt = 
        DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
    

    (But note that it is usually safer to use one of the TryParse() methods in case a date is not in the expected format)

    Make sure to check Custom Date and Time Format Strings when constructing format string, especially pay attention to number of letters and case (e.g. "MM" is Month (01-12) and "mm" is minutes (00-59) ).

    Another useful resource for C# format strings is String Formatting in C#