Search code examples
c#parsingdatetimeformatexceptioniformatprovider

DateTime.Parse with a custom DateTimeFormatInfo throws an exception


Why is this code throwing an exception?

var dateTime = "2012-03-21_15.12";
var format = new DateTimeFormatInfo()
{
   FullDateTimePattern = "yyyy-MM-dd-HH_mm.ss"
};

// FormatException: String was not recognized as a valid DateTime.
var parse = DateTime.Parse(dateTime, format); 

Solution

  • Your format string and the date string do not match.

    You seem to have forgotten either the hours or minutes portion in the date string.

    This:

     var dateTime = "2012-03-21_15.12";
    

    Should probably look like:

    var dateTime = "2012-03-21-15_54.12";
    

    And I suggest using DateTime.ParseExact:

    DateTime.ParseExact("2012-03-21-16_15.12", 
            "yyyy-MM-dd-HH_mm.ss", 
            CultureInfo.InvariantCulture, 
            DateTimeStyles.None)