DateTime.Parse抛出异常在C#抛出、异常、DateTime、Parse

2023-09-05 01:08:16 作者:有一种微笑叫逞强′

我不知道为什么异常被抛出,这里的工作code:

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")

抛出的异常是出现FormatException的,包括与此消息: 字符串未被识别为有效的DateTime。的

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

这里的的CurrentCulture值:

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?

推荐答案

由于有一年只有12个月)

Because there are only 12 months in a year ;)

我猜你的当前区域性设置使用DD / MM / YYYY。无论你使用的字符串指定哪些文化的日期格式,使用解析超负荷解析:

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) 

或使用ParseExact()方法,并指定格式的自己。

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);