Reputation: 433
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 theKind
property of the returnedDateTime
object is set toDateTimeKind.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?
Upvotes: 0
Views: 572
Reputation: 78183
'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.
Upvotes: 2