Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

datetime

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.}
like image 406
Aaryn Avatar asked Feb 24 '11 23:02

Aaryn


1 Answers

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);
like image 137
jevakallio Avatar answered Oct 11 '22 14:10

jevakallio