简体   繁体   中英

DateTime.TryParseExact() not recognizing the PM designator, AM working as expected

I am writing a program to read log files, converting timestamps along the way. Currently, I am using DateTime.TryParseExact() to quickly analyze timestamps, ensuring things are correct. The issue I am running into is only AM designators are being recognized, PM are working without issue. I have isolated the issue in the below snippet:

string format = "M/dd/yyyy H:mm:ss tt";

string teststringPM = "1/21/2019 3:25:32 PM";
string teststringAM = "1/21/2019 3:25:32 AM";

DateTime placeholderPM;
DateTime placeholderAM;

DateTime.TryParseExact(teststringPM, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out placeholderPM);
DateTime.TryParseExact(teststringAM, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out placeholderAM);

Console.WriteLine("placeholderPM:");
Console.WriteLine(placeholderPM.ToString());

Console.WriteLine("placeholderAM:");
Console.WriteLine(placeholderAM.ToString());

The output from this looks like:

placeholderPM:
1/1/0001 12:00:00 AM

placeholderAM:
1/21/2019 3:25:32 AM

We can see that the placeholderPM is the default new datetime value. I have tried changing the IFormatProvider to en-US, without any change in behavior.

Any insight greatly appreciated!

It looks like you might be using the 'H' identifier instead of 'h'. This is an expected behavior as a upper case 'H' is used for 24 hour time. Using a lower case 'h' should resolve this issue.

For example, the format would become:

string format = "M/dd/yyyy h:mm:ss tt";

This goes into more detail

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