Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/277.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# DateTime.TryParseExact可以';t似乎与AM/PM使用“匹配”;tt";_C#_.net_Datetime - Fatal编程技术网

C# DateTime.TryParseExact可以';t似乎与AM/PM使用“匹配”;tt";

C# DateTime.TryParseExact可以';t似乎与AM/PM使用“匹配”;tt";,c#,.net,datetime,C#,.net,Datetime,这里没有。这个问题很简单,但看看网上的一切,我似乎做得对。但是谁能告诉我为什么这个代码不起作用: string testDateString = "2/02/2011 3:04:01 PM"; string testFormat = "d/MM/yyyy h:mm:ss tt"; DateTime testDate = new DateTime(); DateTime.TryParseExact(testDateString, testFormat, null, 0, out testDate)

这里没有。这个问题很简单,但看看网上的一切,我似乎做得对。但是谁能告诉我为什么这个代码不起作用:

string testDateString = "2/02/2011 3:04:01 PM";
string testFormat = "d/MM/yyyy h:mm:ss tt";
DateTime testDate = new DateTime();
DateTime.TryParseExact(testDateString, testFormat, null, 0, out testDate);

// Value of testDate is the default {1/01/0001 12:00:00 a.m.}
但是仅仅从字符串日期中删除AM/PM和从格式中删除“tt”就可以按预期工作了吗

string testDateString = "2/02/2011 3:04:01";
string testFormat = "d/MM/yyyy h:mm:ss";
DateTime testDate = new DateTime();
DateTime.TryParseExact(testDateString, testFormat, null, 0, out testDate);

// Value of testDate is the expected {2/02/2011 3:04:01 a.m.}
尽管名称准确,
DateTime.TryParseExact()
仍依赖于系统区域性来解析日期。尝试指定使用AM/PM符号的区域性,例如
en US

DateTime.TryParseExact(testDateString, testFormat, new System.Globalization.CultureInfo("en-US"), DateTimeStyles.None, out testDate);

必须指定实际使用AM/PMdesignators的区域性,例如Brittish CultureInfo:

DateTime.TryParseExact(testDateString, testFormat, CultureInfo.GetCultureInfo("en-GB"), 0, out testDate);

您应该注意TryParseExact()的返回值。你这是假的。改用ParseExact,现在您得到了一个很好的异常。