Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I get the timezone offset of the physical server running my code? Not some date object or other object in memory.

For example, the following code will output -4:00:00:

<%= TimeZone.CurrentTimeZone.GetUtcOffset(new DateTime()) %>

When it should be -03:00:00 because of daylight savings

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
694 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

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);

(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.)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...