Get Timezone Offset of Server in C#

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

Leave a Comment

error code: 521