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,现在您得到了一个很好的异常。