0

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);
1
  • How could I know the specified timezone offset on my PC?
    – Bryan
    Mar 25, 2014 at 15:23

2 Answers 2

4

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;
1
  • 1
    You did it man!! It works!! TimeZoneInfo.ClearCachedData() is a tweak. Thanks!
    – Bryan
    Mar 25, 2014 at 15:46
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.