DateTime.Now or DateTime.UtcNow

2

What is the difference between DateTime.Now and DateTime.UtcNow ?

DateTime dateNow = DateTime.Now; // retorna {01/08/2018 18:28:15}
DateTime dateUtfNow = DateTime.UtcNow; // retorna {01/08/2018 21:28:15}

My computer clock looks like: 18:28 and the date 08/01/2018 .

The difference I saw was 3 hours more. When should I use Now and UtcNow .

    
asked by anonymous 01.08.2018 / 23:32

1 answer

6

The DateTime.Now returns the time set on the server and the DateTime.UtcNow returns the time in UTC which is the "Coordinated Universal Time" , in this case we have 3 hours difference just because you are running on your machine that is in Brazil and most of the Brazilian states have a time zone of "- 3 hours" , in the map in the link of Wikpedia you can see the states of Brazil with different hours: p>

If you set your computer to use the Acre state time zone you would probably see a difference of -5 hours compared to DateTime.UtcNow .

Already using the method:

Console.WriteLine( DateTimeOffset.Now.ToUnixTimeMilliseconds() );

Or:

Console.WriteLine( DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() );

You will get equal results , because the ToUnixTimeMilliseconds method works with UTC too, ie the Unix Epoch is based on UTC so the class internally probably compensates for the " time zone "

Imagine that you have two individuals:

  • Paulo in Acre (-5 hours UTC)
  • Sofia in São Paulo (-3 hours on UTC)

Paulo sends a message to Sofia as 18:01 (time in Acre):

  

I finished the prototype of the app, follow the link to test - Time: 18:01 ✓✓

Sofia will see it at almost the same time it was sent, but for her she will be 20:01 and will reply back 30 minutes later:

  

Thank you Paul, I tested the app, it looks like it's inside the combo, I'm waiting for the publication in the store - Time: 20:31 ✓✓

John will receive the message at the same time, but he will see the message as his local time, which would be 18:31 :

  

Thank you Paulo, I tested the app, it seems that it is inside the combo, I wait for the publication in the store - Time: 18:31 ✓✓

In other words, saving the timezone with the person's timezone would probably cause problems, now if you use your hypothetical UTC database without applying timezone, either with Unix-time or by the bank itself, it is enough at the moment read the application to identify the timezone of the user who is reading the message and adjust the value entered in the database for the region of the message.

    
01.08.2018 / 23:36