Вопрос

I have no idea why exception was thrown, here's the working code:

DateTime.Parse("1/12/2012 12:00:00 AM")

And this is the one which throw exception:

DateTime.Parse("1/13/2012 12:00:00 AM")

Exception thrown is "FormatException", include with this message: "String was not recognized as a valid DateTime."

Here's the CurrentCulture value:

System.Globalization.CultureInfo.CurrentCulture
{en-MY}
Calendar: {System.Globalization.GregorianCalendar}
CompareInfo: {CompareInfo - en-MY}
CultureTypes: SpecificCultures | InstalledWin32Cultures
DateTimeFormat: {System.Globalization.DateTimeFormatInfo}
DisplayName: "English (Malaysia)"
EnglishName: "English (Malaysia)"
IetfLanguageTag: "en-MY"
IsNeutralCulture: false
IsReadOnly: true
KeyboardLayoutId: 17417
LCID: 17417
Name: "en-MY"
NativeName: "English (Malaysia)"
NumberFormat: {System.Globalization.NumberFormatInfo}
OptionalCalendars: {System.Globalization.Calendar[2]}
Parent: {en}
TextInfo: {TextInfo - en-MY}
ThreeLetterISOLanguageName: "eng"
ThreeLetterWindowsLanguageName: "ENM"
TwoLetterISOLanguageName: "en"
UseUserOverride: true

Anyone know what is going on here?

Это было полезно?

Решение

Because there are only 12 months in a year ;)

I'm guessing your current culture setting uses 'dd/MM/yyyy'. Either specify which culture's date format you're using for the string to be parsed using the overload of Parse:

DateTime.Parse(String, IFormatProvider) 

or use the ParseExact() method and specify the format yourself.

var provider = CultureInfo.InvariantCulture;
var format = "M/dd/yyyy hh:mm:ss tt";

DateTime.ParseExact("1/13/2012 12:00:00 AM", format, provider);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top