Home > Enterprise >  Why my current time zone in app is not changing?
Why my current time zone in app is not changing?

Time:01-26

I'm new with c# and timezone. I'm currently creating an app with a timezone.

I have this code to get the current timezone of my local machine.

 private void btnGetCurrentTimeZone_Click(object sender, EventArgs e)
 {
     TimeZone localZone = TimeZone.CurrentTimeZone;
     lblShowTimeZone.Text = "TimeZone: "   localZone.StandardName;
 }

My problem is when I run the app and click the button for the first time I got the correct timezone. But when I change the system timezone on settings and click again the button, the timezone value did not change. I need to close the app and run again to get the correct timezone.

CodePudding user response:

Use TimeZoneInfo instead TimeZone , because TimeZone is deprecated

TimeZoneInfo localZone = TimeZoneInfo.Local;
TimeZoneInfo.ClearCachedData();
lblShowTimeZone.Text = "TimeZone: "   localZone.StandardName;

CodePudding user response:

For efficiency, instead of calling TimeZoneInfo.ClearCachedData() every time you call TimeZoneInfo.Local, you can set an event handler to do this when the system time zone changes:

// in some startup init method for your application
SystemEvents.TimeChanged  = (s, e) => TimeZoneInfo.ClearCacheData();

Now this will only be cleared when/if a user changes the system time zone and you can use TimeZoneInfo.Local throughout your application and be confident it reflects the current system time zone and you get the benefit of having that value cached most of the time so it doesn't need to callout to some Win32 method to get the current value everytime.

CodePudding user response:

When you invoke TimeZone.CurrentTimeZone, it caches the current time zone. So you need to reset it.

But the ResetTimeZone method is NonPublic, so Reflection is necessary here.

private static void ResetTimeZone() 
{
    var tzType = typeof(TimeZone);
    var rtzMethod = tzType.GetMethod("ResetTimeZone", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
    rtzMethod?.Invoke(null, null);
}

Before you get the current time zone use the reset method.

private void btnGetCurrentTimeZone_Click(object sender, EventArgs e)
{
    ResetTimeZone(); // reset

    TimeZone localZone = TimeZone.CurrentTimeZone;
    lblShowTimeZone.Text = "TimeZone: "   localZone.StandardName;
}
  •  Tags:  
  • Related