在C#中获取时区偏移服务器 [英] Get Timezone Offset of Server in C#
问题描述
我怎样才能获得时区运行我的code物理服务器的偏移?在内存而不是一些日期对象或其它对象。
How can I get the timezone offset of the physical server running my code? Not some date object or other object in memory.
例如,下面的code将输出 -4:00:00
:
For example, the following code will output -4:00:00
:
<%= TimeZone.CurrentTimeZone.GetUtcOffset(new DateTime()) %>
当它应该是 -03:00:00
由于夏令
推荐答案
新的日期时间()
会给你1月1日0001,而不是电流日期/时间。我怀疑你想要的电流的UTC偏移......,这就是为什么你没有看到夏令在当前code抵消。
new DateTime()
will give you January 1st 0001, rather than the current date/time. I suspect you want the current UTC offset... and that's why you're not seeing the daylight saving offset in your current code.
我会使用<一个href="http://msdn.microsoft.com/en-us/library/system.timezoneinfo.local.aspx"><$c$c>TimeZoneInfo.Local$c$c>而不是 TimeZone.CurrentTimeZone
- 它的可以的没有影响的东西,但它肯定是一个更好的办法。 <一href="http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx"><$c$c>TimeZoneInfo$c$c>应该pretty的所有code多替换时区
。然后你可以使用 GetUtcOffset
:
I'd use TimeZoneInfo.Local
instead of TimeZone.CurrentTimeZone
- it may not affect things, but it would definitely be a better approach. TimeZoneInfo
should pretty much replace TimeZone
in all code. Then you can use GetUtcOffset
:
var offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);
(使用 DateTime.Now
的应该的工作很好,但它涉及到幕后的一些魔法的时候有夏令转换现在各地。 的DateTime
实际上具有的四的种类,而不是标榜3 的,但它只是简单使用 UtcNow
来避免这个问题完全是。)
(Using DateTime.Now
should work as well, but it involves some magic behind the scenes when there are daylight saving transitions around now. DateTime
actually has four kinds rather than the advertised three, but it's simpler just to avoid the issue entirely by using UtcNow
.)
或者你当然可以用我的野田佳彦时间库,而不是这一切的BCL垃圾;)(如果你做了很多日期/时间的工作,我会全力推荐的 - 很明显 - 但如果你的只有的这样一个位,它很可能是矫枉过正)
Or of course you could use my Noda Time library instead of all this BCL rubbish ;) (If you're doing a lot of date/time work I'd thoroughly recommend that - obviously - but if you're only doing this one bit, it would probably be overkill.)
这篇关于在C#中获取时区偏移服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!