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.}
似乎为我工作得很好... – SwDevMan81 2011-02-24 23:30:24
你应该注意TryParseExact()的返回值。你在这里弄虚作假。相反,使用ParseExact,现在你会得到一个很好的例外。 – 2011-02-24 23:55:16