Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
697 views
in Technique[技术] by (71.8m points)

.net - Get Timezone Offset of Server in C#

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...