Question

Im currently developing on asp - c# as a backend code. I want to get the current timezone that was set on the PC.

The below code are still identifying what is the correct timezone of my current area (+8GMT) even though I already changed my PC timezone settings into another timezone.

What I want is to get the timezone offset specified on the PC date settings. Can anyone help me on this. Below is my code so far.

public TimeSpan currentOffset;
public DateTime utc;
public DateTime local;

this.utc = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, TimeZoneInfo.Utc.Id);
this.local = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, TimeZoneInfo.Local.Id);
this.currentOffset = this.local.Subtract(this.utc);
Was it helpful?

Solution

In addition to David Haney's answer.

TimeZoneInfo is caching data after first call so any changes in PC settings will not affect your application if it is already running. You should call method:

 TimeZoneInfo.ClearCachedData();

to refresh this cache. So this one will work in your case:

 TimeZoneInfo.ClearCachedData();
 var offsetTimespan = DateTimeOffset.Now.Offset;
 var offsetInHours = offsetTimespan.TotalHours;

OTHER TIPS

You're making your life harder than it needs to be. :)

Use DateTimeOffset: http://msdn.microsoft.com/en-us/library/system.datetimeoffset.now%28v=vs.110%29.aspx

var now = DateTimeOffset.Now;

This will include the time zone offset information as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top