Let's imagine that this little program runs:
while (true) { Console.WriteLine($"{DateTime.UtcNow} -> {DateTime.Now} tz={TimeZone.CurrentTimeZone.StandardName} / {TimeZoneInfo.Local.StandardName}"); await Task.Delay(TimeSpan.FromSeconds(1)); }
When I change the system's time zone when the program is running the app does not see the change. The timezone and the time is as if the timezone has not changed.
In order for the app to display the new time and time zone I need to restart the app.
If I change the system time the time change is picked up immediately.
It would be great if you could help me with three questions:
Here's a little screenshot to show the .NET app using time different than the operating system:
BTW. On Windows IOT on Raspberry Pi, my experiment shows that if I restart the app it will show the new timezone, but the 'old' time. The new time will be picked up after restarting the the system.
The DateTime. Now property returns the current date and time, for example 2011-07-01 10:09.45310 . The DateTime. Today property returns the current date with the time compnents set to zero, for example 2011-07-01 00:00.00000 .
The Now property returns a DateTime value that represents the current date and time on the local computer.
The property UtcNow of the DateTime class returns the current date and time of the machine running the code, expressed in UTC format. UTC is a universal format to represent date and time as an alternative to local time. Also known as the GMT+00 timezone.
You should always try to work with DateTime objects that have Kind=Utc , except during i/o (displaying and parsing). This means you should almost always be using DateTime. UtcNow , except for the cases where you're creating the object just to display it, and discard it right away.
You can check the following msdn link. It clearly states the following :
Notes to Callers: Local time zone data is cached after CurrentTimeZone is first used to retrieve time zone information. If the system's local time zone subsequently changes, the CurrentTimeZone property does not reflect this change. If you need to handle time zone changes while your application is running, use the TimeZoneInfo class and call its TimeZoneInfo.ClearCachedData method.
is this documented anywhere? Yes, as stated above.
why isn't the timezone change picked up while the application is running? Because the timezone information is cached.
can I do anything so that the app picks up timezone changes while it's running? Yes, by using the TimeZoneInfo class and calling its TimeZoneInfo.ClearCachedData method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With