Search code examples
c#datetimeparsingdatetime-format.net-core-2.1

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?


Solution

  • 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;
    }