2011-02-24 92 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);