2011-02-24 90 views
7

C#noob here。简单的问题,但在网上看到的一切,我似乎是这样做的权利。但谁能告诉我为什么这个代码是行不通的:DateTime.TryParseExact似乎无法匹配上午/下午使用“tt”

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.} 

但是简单地删除从字符串日期从格式的“TT”的AM/PM按预期工作?

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.} 
+3

似乎为我工作得很好... – SwDevMan81 2011-02-24 23:30:24

+0

你应该注意TryParseExact()的返回值。你在这里弄虚作假。相反,使用ParseExact,现在你会得到一个很好的例外。 – 2011-02-24 23:55:16

回答

7

尽管确切名,DateTime.TryParseExact()取决于系统的文化解析日期。尝试指定在使用的AM/PM符号文化,如en-US

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

啊,非常感谢! – Aaryn 2011-02-24 23:34:55

3

您必须指定实际使用AM/PMdesignators,例如Br​​ittish CultureInfo的文化:

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