简体   繁体   中英

ParseExact and TryParseExact not working as expected

I am trying to convert several different times of time, tried with DateTime.ParseExact and DateTime.TryParseExact and both didn't worked for me.

The data I have to parse is in the following formats:

5 PM
1:00
1:00 AM
12:00
18:00

I've tried the following:

DateTime.TryParseExact(stDate, "H:mm", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out visStartHour);

visStartHour = DateTime.ParseExact(stDate, "H:mm", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);

I have also tried to use a string array of formats and none works:

string[] timeFormats = new string[] { "H tt", "H:mm tt", "HH:mm", "H:mm" };

Also tried using:

System.Globalization.DateTimeStyles.AllowWhiteSpaces

Just use TryParse()

DateTime result;

DateTime.TryParse("5 PM", out result);
DateTime.TryParse("1:00", out result);
DateTime.TryParse("1:00 AM", out result);
DateTime.TryParse("12:00", out result);
DateTime.TryParse("18:00", out result);

etc...

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