【问题标题】:DateTime.ParseExact Method not recognizing "Z" as UTC timeDateTime.ParseExact 方法无法将“Z”识别为 UTC 时间
【发布时间】:2019-04-04 02:35:39
【问题描述】:

我正在尝试读取日志文件,将时间戳提取为日期时间对象。其中一些时间采用 UTC 格式,尾随“Z”。我在我们的格式中包含了“K”,但是,日期时间仍然不能被识别为 UTC。 相反,它被视为未指定。

下面代码的sn-p:

string teststring = line.Substring(OffsetStart, format.Length);
DateTime datePlaceholder;

if (DateTime.TryParseExact(teststring, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out datePlaceholder))
{
    Format = format;
    OffsetEnd = OffsetStart + format.Length;
    FormatLen = format.Length;
        return datePlaceholder;
    break;
}

我遍历了几个不同的格式字符串,例如,这里是一个:

yyyy-MM-ddTHH:mm:ss.fffK

感谢任何见解!

【问题讨论】:

    标签: c# datetime


    【解决方案1】:

    看来你需要使用:

    System.Globalization.DateTimeStyles.AdjustToUniversal
    

    代替

    System.Globalization.DateTimeStyles.None
    

    所以整行是:

    if (DateTime.TryParseExact(teststring, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal, out datePlaceholder))
    {do whatever}
    

    【讨论】:

    • 完美运行!谢谢你:)
    • AdjustToUniversal总是将值调整为 UTC。这不一定是错误的,但如果输入字符串可能不同,那么请考虑 RoundTripKind,这将调整 if 输入字符串为 UTC(在这种格式中,当 Z 出现在用K 说明符标记的位置)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 2022-11-05
    • 1970-01-01
    • 2023-04-09
    • 2011-10-01
    • 2021-11-21
    • 2016-04-19
    相关资源
    最近更新 更多