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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With