Domanda

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); 
È stato utile?

Soluzione

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)

Altri suggerimenti

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

DateTime.ParseExact

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top