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
The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time. If the returned value is positive, local timezone is behind the UTC and if it is negative, the local timezone if ahead of UTC.
A zone offset is the difference in hours and minutes between a particular time zone and UTC. In ISO 8601, the particular zone offset can be indicated in a date or time value. The zone offset can be Z for UTC or it can be a value "+" or "-" from UTC.
A UTC offset is the difference in hours and minutes between a particular time zone and UTC, the time at zero degrees longitude. For example, New York is UTC-05:00, which means it is five hours behind London, which is UTC±00:00.
The DateTimeOffset structure includes a DateTime value, together with an Offset property that defines the difference between the current DateTimeOffset instance's date and time and Coordinated Universal Time (UTC).
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.)
Since .NET 3.5, you can use the following from DateTimeOffset
to get the current offset.
var offset = DateTimeOffset.Now.Offset;
MSDN documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With