문제

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);
도움이 되었습니까?

해결책

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;

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top