简体   繁体   English

DateTime.TryParseExact 无法按预期使用格式“M/d/yyyy h:mm:ss tt”

[英]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.我正在尝试使用 DateTime.TryParseExact function 将诸如“5/10/2020 8:15:10 AM”之类的时间戳解析为DateTime.TryParseExact object。 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.当我尝试使用示例中的格式解析时间戳时,function 返回false ,我只是找不到我使用的格式有任何问题。 Is there anything I am missing here?我在这里有什么遗漏吗?

It will work for you, AssumeUniversal differs value based on timezone.它会为你工作, AssumeUniversal根据时区的不同而不同。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM