Richard Baluyut
Richard Baluyut

Reputation: 15

Why my current time zone in app is not changing?

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.

Upvotes: 1

Views: 448

Answers (2)

Ubaldo Vitiello
Ubaldo Vitiello

Reputation: 221

Use TimeZoneInfo instead of TimeZone; TimeZone is deprecated reference documentation.

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

Upvotes: 0

Kevin Brock
Kevin Brock

Reputation: 8944

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.

Upvotes: 2

Related Questions