简体   繁体   中英

DateTime.TryParseExact can't seem to match AM/PM using “tt”

C# noob here. Simple question, but looking at everything online, I seem to be doing this right. But can anyone tell me why this code wouldn't work:

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

But simply removing the AM/PM from the string date and the "tt" from the format works as expected?

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

Despite its exact name, DateTime.TryParseExact() depends on the system culture to parse dates. Try specifying a culture where the AM/PM notation is used, such as en-US :

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM