Are UtcNow and Now the same time? Do they know that they are different?

If I run a fragment, for example:

bool areTheyTheSame = DateTime.UtcNow == DateTime.Now 

what will I get? Does DateTime return its timezone so I can compare?

My particular problem is that I am trying to create a cache-like API. If DateTime AbsoluteExpiration is required, do I need to force my API users to know whether to give me UTC or time in the time zone?

[Edit] This SO question is very important for my problem: Cache.Add absolute expiration - UTC or not?

[Edit] To clarify for future readers, DateTimeKind is what is different. Undefined DateTimeKind is often a problem, and this is what you get, for example, when retrieving from a database. Set DateTimeKind in the DateTime constructor ...

[Edit] JonSkeet wrote a great blog post condemning this behavior and offering a solution: http://noda-time.blogspot.co.uk/2011/08/what-wrong-with-datetime-anyway.html

+4
source share
3 answers

Did you really try the snippet yourself?

They are different, and direct comparison does not take into account the difference, but you can convert local to UTC by calling ToUniversalTime .

 var now = DateTime.Now; var utcNow = DateTime.UtcNow; Console.WriteLine(now); // 12/07/2010 16:44:16 Console.WriteLine(utcNow); // 12/07/2010 15:44:16 Console.WriteLine(now.ToUniversalTime()); // 12/07/2010 15:44:16 Console.WriteLine(utcNow.ToUniversalTime()); // 12/07/2010 15:44:16 Console.WriteLine(now == utcNow); // False Console.WriteLine(now.ToUniversalTime() == utcNow); // True Console.WriteLine(utcNow.ToUniversalTime() == utcNow); // True 
+6
source

Also be careful when using the local DateTime and calling .ToUniversalTime() when daylight saving time occurs.

See the note in the comments section here: http://msdn.microsoft.com/en-us/library/system.timezone.touniversaltime.aspx

+2
source

DateTime.Now returns the system time, and DateTime.UtcNow returns the UTC time.

0
source

Source: https://habr.com/ru/post/1315412/


All Articles