32

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?

Andrei M
  • 3,429
  • 4
  • 28
  • 35

3 Answers3

47

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.

Allan
  • 1,063
  • 10
  • 18
  • Perfect! +1 for no external libraries and properly handling non-60 minute offsets. – Master of Ducks Sep 17 '19 at 10:26
  • Is there a case when offset can contain a value for minutes which is not zero e.g. +03:45 ? I guess not, therefore it could be even simplified to take into account hours only. – Darko Vasilev Nov 30 '21 at 13:44
  • @DarkoVasilev yes, there are several timezones with offsets that are not to the hour. For example, India is at UTC+5:30. There's a New Zealand / Chatham Islands timezone at UTC +12:45 / +13:45 – Allan Mar 14 '22 at 22:28
21

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"
Chris W.
  • 37,583
  • 36
  • 99
  • 136
  • 1
    Is there a clean way to get an integer value for UTC offset from moment.js? – quemeful Dec 07 '22 at 20:42
  • 1
    @quemeful utc offset is not necessarily in full hours. It can be 15 mins for instance. So you can get a decimal of hours -8.5 or an integer of mins. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset – Chris W. Dec 19 '22 at 21:38
16
<script type="text/javascript">

var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
document.write("The local time zone is: GMT " + gmtHours);

</script>
Vadim Gulyakin
  • 1,415
  • 9
  • 7