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

前端 未结 4 1141
抹茶落季
抹茶落季 2020-11-29 02:39

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 -

4条回答
  •  日久生厌
    2020-11-29 02:55

    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.

提交回复
热议问题