Вопрос

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); 
Это было полезно?

Решение

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)

Другие советы

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

DateTime.ParseExact

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top