Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET DateTime.Now returns incorrect time when time zone is changed

This problem occurred during daylight saving time change. After the change occurred, we've noticed that our server application started writing into the log incorrect time - one hour ahead which means that .NET caches time zone offset. We had to restart our application to resolve this problem. I wrote a simple application to reproduce this problem. When I change the time zone while application is running, DateTime.Now property keeps producing the time in the old time zone. Does anybody know if there is a workaround for this problem apart from restarting the application?

like image 771
GregK Avatar asked Nov 17 '08 21:11

GregK


People also ask

How accurate is DateTime now in C#?

It tends to be between 0.5 and 15 milliseconds.

Does C# DateTime have a timezone?

DateTime itself contains no real timezone information.

Does DateTime now return UTC time?

Get current time in UTC format using datetime. For that, you can use the datetime module's now() function. In the now() function, you can pass the timezone information, and it returns the current time in that timezone. It returned the timezone aware datetime object, which contains the current time in the UTC timezone.

What does DateTime now return C#?

Remarks. The Now property returns a DateTime value that represents the current date and time on the local computer.


1 Answers

Yes, the current time zone is cached. For a good reason, it avoids trouble with broken code that uses DateTime.Now to implement elapsed time measurement. Such code tends to suffer a heart-attack when the time suddenly changes by an hour or more.

You will have to call System.Globalization.CultureInfo.ClearCachedData() to reset the cached value. The next call to DateTime.Now will now give the new local time. If you use the .NET 3.5 TimeZoneInfo class at all then you'll also need to call its ClearCachedData() method. You can use the SystemEvents.TimeChanged event as a trigger.

like image 159
Hans Passant Avatar answered Sep 20 '22 22:09

Hans Passant