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

C # noob here. A simple question, but looking at everything online, I seem to be doing it right. But can anyone tell me why this code is not working:

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

But just remove AM / PM from the string date, and does "tt" from the format work 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 am} 
+7
source share
2 answers

Despite its exact name, DateTime.TryParseExact() depends on the system culture for parsing dates. Try specifying a culture that uses the AM / PM notation, for example en-US :

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

You must specify a culture that actually uses AM / PMdesignators, such as Brittish CultureInfo:

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

All Articles