简体   繁体   English

DateTime.TryParseExact 的结果有 DateTimeKind.Unspecified 尽管输入的日期时间字符串包含时区信息

[英]DateTime.TryParseExact's result has DateTimeKind.Unspecified despite the input date time string contains timezone information

string dateTimeStr = "2020-01-02T04:00:00Z";
string[] formats = { "yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd'T'HH:mm:ss.fff'Z'" };

if (DateTime.TryParseExact(dateTimeStr, formats,
                        null,
                        DateTimeStyles.None,
                        out DateTime dateValue))
{
    Console.WriteLine(dateValue.Kind); // why set to DateTimeKind.Unspecified here?
}
else
{
    Console.WriteLine(dateValue);
}

By this documentation :通过此文档

If s contains time zone information, the time is converted to local time, if necessary, and the Kind property of the returned DateTime object is set to DateTimeKind.Local .如果s包含时区信息,则根据需要将时间转换为本地时间,并将返回的DateTime object 的Kind属性设置为DateTimeKind.Local

However, in the commented line, the dateValue 's Kind field is set to DateTimeKind.Unspecified , despite the tailing 'Z' in the dateTimeStr to specify its timezone as Utc.但是,在注释行中, dateValueKind字段设置为DateTimeKind.Unspecified ,尽管dateTimeStr中的尾随“Z”将其时区指定为 Utc。

I don't know how it happens and my goad is to have the output DateTime has its Kind set to DateTimeKind.Utc .我不知道它是怎么发生的,我的目标是让 output DateTimeKind设置为DateTimeKind.Utc How could I achieve that?我怎么能做到这一点?

'Z' is just an escaped literal letter Z that does not mean anything (same for the 'T' ). 'Z'只是一个转义的字面字母 Z,它没有任何意义(对于'T'也是如此)。 The time zone specifier in the format string is K .格式字符串中的时区说明符K

string[] formats = { "yyyy-MM-ddTHH:mm:ssK", "yyyy-MM-ddTHH:mm:ss.fffK" };

This will give you DateTimeKind.Local like documented, and then you call .ToUniversalTime() on the result to get to the UTC.这将为您提供DateTimeKind.Local像记录的那样,然后您在结果上调用.ToUniversalTime()以获取 UTC。

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

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