Search code examples
c#datetimetimezonewindows-services

Request New System Time on Runtime when Timezone Changes


I have a windows service that monitors System Events when the local system timezone has changed, which then executes an event querying for the new TimeZone and new System Time. I followed [Microsoft documentation][1] but i cannot get the new System Time using DateTime.Now.ToLongTimeString() after the Timezone Changes. How can I solve this issue?

Debugging TimeZone.CurrentTimeZone

I also found that the TimeZone.CurrentTimezone does not update the Standard Timezone but only the DaylightName after the TimeZone changed on the system. Logs when TimeZone Changes

Ideally i'd like to not only get the new System Time but TimeZone Standard Name as well. But with the New System Time and Daylight Name i can implement the rest of my application.

See my code below:

 //when service starts
    public void Start()
    {

        //timer stops
        _timer.Start();

        //Event when services Starts
        ServiceStarted();

        //Getting access to the System Events, and monitoring for time Zone changes.
        SystemEvents.TimeChanged += SystemEvents_TimeChanged;


    }

    //System Time event when Time Changes
    private void SystemEvents_TimeChanged(object sender, EventArgs e)

    {
        TimeZoneInfo.Local.ToString();
        TimeZone.CurrentTimeZone.ToString();

                    string[] lines = new string[]
        {
            $"{DateTime.Now.ToString()} The Local System Time has changed",
            $"{DateTime.Now.ToString()} Previous Time zone {TimeZoneInfo.Local.DaylightName.ToString()}",
            $"{DateTime.Now.ToString()} New Time Zone {TimeZone.CurrentTimeZone.DaylightName.ToString()} and the time is {DateTime.Now.ToLongTimeString()}"


        };

        //create log file and add the event message
        File.AppendAllLines(@"C:\Temp\Heartbeat_Log.txt", lines);
    }

Solution

  • .Net caches the system local time zone for performance reasons, so if you're specifically watching for changes, you'll need to clear the cache.

    In your event handler, call:

    TimeZoneInfo.ClearCachedData();
    

    https://learn.microsoft.com/dotnet/api/system.timezoneinfo.clearcacheddata

    Also, the TimeZone class is deprecated. Use only TimeZoneInfo.