In C# you can use
System.TimeZone.CurrentTimeZone.GetUtcOffset(someDate).Hours
But how can I get UTC offset in hours for a certain date (Date object) in javascript?
Vadim's answer might get you some decimal points after the division by 60; not all offsets are perfect multiples of 60 minutes. Here's what I'm using to format values for ISO 8601 strings:
function pad(value) { return value < 10 ? '0' + value : value; } function createOffset(date) { var sign = (date.getTimezoneOffset() > 0) ? "-" : "+"; var offset = Math.abs(date.getTimezoneOffset()); var hours = pad(Math.floor(offset / 60)); var minutes = pad(offset % 60); return sign + hours + ":" + minutes; }
This returns values like "+01:30" or "-05:00". You can extract the numeric values from my example if needed to do calculations.
Note that getTimezoneOffset()
returns a the number of minutes difference from UTC, so that value appears to be opposite (negated) of what is needed for formats like ISO 8601. Hence why I used Math.abs()
(which also helps with not getting negative minutes) and how I constructed the ternary.
I highly recommend using the moment.js library for time and date related Javascript code.
In which case you can get an ISO 8601 formatted UTC offset by running:
> moment().format("Z") > "-08:00"
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