Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C中的DateTime.Parse抛出异常#_C#_.net_Parsing_Datetime_Formatexception - Fatal编程技术网

C# C中的DateTime.Parse抛出异常#

C# C中的DateTime.Parse抛出异常#,c#,.net,parsing,datetime,formatexception,C#,.net,Parsing,Datetime,Formatexception,我不知道为什么会抛出异常,下面是工作代码: DateTime.Parse("1/12/2012 12:00:00 AM") 这是引发异常的一个: DateTime.Parse("1/13/2012 12:00:00 AM") 引发的异常为“FormatException”,包括此消息: “字符串未被识别为有效的日期时间。” 以下是CurrentCulture值: System.Globalization.CultureInfo.CurrentCulture {en-MY} Calendar:

我不知道为什么会抛出异常,下面是工作代码:

DateTime.Parse("1/12/2012 12:00:00 AM")
这是引发异常的一个:

DateTime.Parse("1/13/2012 12:00:00 AM")
引发的异常为“FormatException”,包括此消息: “字符串未被识别为有效的日期时间。”

以下是CurrentCulture值:

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

有人知道这里发生了什么吗?

因为一年只有12个月;)

我猜您当前的区域设置使用“dd/MM/yyyy”。使用Parse重载指定要解析的字符串所使用的区域性日期格式:

DateTime.Parse(String, IFormatProvider) 
或者使用ParseExact()方法并自己指定格式

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

DateTime.ParseExact("1/13/2012 12:00:00 AM", format, provider);

你确定你的代码里没有错别字吗?此外,请查看Hmm,您的文化使用dd/mm/yyyy格式,这可能会让您感到痛苦。一年中没有13个月,只有12个月。系统的价值是什么。全球化。文化信息。当前文化?@codekaizen你是说当前文化的价值是什么?当前文化是一种价值。。。它是一个CultureInfo实例。我指的是那个例子。要么是yyyy/mm/dd,要么是相反,而且似乎去年:)+1的文化背景很好。我在想也许编译器是迷信的,不喜欢13号星期五:)你试了哪一个?您是如何将日期值转换为字符串的?请尝试:DateTime.ParseExact(“1/13/2012 12:00:00 AM”,“M/dd/yyyy hh:mm:ss tt”,System.Globalization.CultureInfo.InvariantCulture)。我也会修改我的答案。不客气。为了完全避免这个问题,请在将日期转换为字符串时指定格式,以便在转换回日期时可以使用该格式。