简体   繁体   English

在C#上获取PC TimeZone

[英]Get PC TimeZone on C#

Im currently developing on asp - c# as a backend code. 我目前正在开发ASP-C#作为后端代码。 I want to get the current timezone that was set on the PC. 我想获取在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. 即使我已经将PC时区设置更改为另一个时区,下面的代码仍在标识当前区域(+ 8GMT)的正确时区。

What I want is to get the timezone offset specified on the PC date settings. 我想要的是获取PC日期设置上指定的时区偏移量。 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. 除了David Haney的答案。

TimeZoneInfo is caching data after first call so any changes in PC settings will not affect your application if it is already running. TimeZoneInfo会在首次调用后缓存数据,因此PC设置中的任何更改都不会影响您的应用程序(如果已运行)。 You should call method : 您应该调用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 使用DateTimeOffsethttp : //msdn.microsoft.com/zh-cn/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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM