简体   繁体   中英

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 .

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.

I don't know how it happens and my goad is to have the output DateTime has its Kind set to DateTimeKind.Utc . How could I achieve that?

'Z' is just an escaped literal letter Z that does not mean anything (same for the 'T' ). The time zone specifier in the format string is 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.

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