简体   繁体   中英

DateTime.TryParseExact not working as expected with format “M/d/yyyy h:mm:ss tt”

I am trying to parse timestamps such as "5/10/2020 8:15:10 AM" into a DateTime object using the DateTime.TryParseExact function. Here is an example for how I am trying to do it:

if (DateTime.TryParseExact(
        "5/10/2020 8:15:10 AM",
        "M/d/yyyy h:mm:ss tt",
        null,
        System.Globalization.DateTimeStyles.AssumeUniversal,
        out DateTime result
        ))
{
    ...
}

When I try to parse the timestamp using the format from the example, the function returns false and I just cannot find anything wrong with the format that I am using. Is there anything I am missing here?

It will work for you, AssumeUniversal differs value based on timezone.

if (DateTime.TryParseExact(
        "5/10/2020 8:15:10 AM",
        "M/d/yyyy h:mm:ss tt",
        DateTimeFormatInfo.InvariantInfo,
        System.Globalization.DateTimeStyles.AdjustToUniversal,
        out DateTime result
        ))
{
    bool fl = true;
}

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