Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTimeKind.Utc vs DateTimeKind.Local

Tags:

c#

Both of these produce the same result but I expected them to be off by 6 hours. What am I not understanding?

Console.WriteLine(new DateTime(1970, 1, 1, 12, 1, 0, DateTimeKind.Utc).ToString("R"));
\\ Thu, 01 Jan 1970 12:01:00 GMT

Console.WriteLine(new DateTime(1970, 1, 1, 12, 1, 0, DateTimeKind.Local).ToString("R"));
\\ Thu, 01 Jan 1970 12:01:00 GMT
like image 386
andleer Avatar asked Mar 07 '23 03:03

andleer


2 Answers

ToString prints the DateTime as is. You have to convert them both to the same kind to be able to see the difference: add .ToUniversalTime():

Console.WriteLine(new DateTime(1970, 1, 1, 12, 1, 0, DateTimeKind.Utc).ToUniversalTime().ToString("R"));
// Thu, 01 Jan 1970 12:01:00 GMT

Console.WriteLine(new DateTime(1970, 1, 1, 12, 1, 0, DateTimeKind.Local).ToUniversalTime().ToString("R"));
// Thu, 01 Jan 1970 11:01:00 GMT <-- I am at GMT+1
like image 162
Patrick Hofman Avatar answered Mar 17 '23 02:03

Patrick Hofman


It's related to the format you're using.

According to Microsoft documentation:

The "R" or "r" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.RFC1123Pattern property. The pattern reflects a defined standard, and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'". When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.

EDIT : "R" or "r" format do not say that the time shown is UTC time. It just say that they use the format "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'". The GMT string is a bit confusing but it's just a string without meaning here ...

like image 33
sheep Avatar answered Mar 17 '23 00:03

sheep