Frage

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); 
War es hilfreich?

Lösung

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)

Andere Tipps

You may want to use DateTime.ParseExact as this will take a datetime format pattern as a parameter.

DateTime.ParseExact

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top