javascriptdatetimetimezoneutcdayjs

How to get the timezone offset for a specific timezone?


I need to sort cities based on their timezone (as TZ identifiers). To do so, the most natural way I found was to compare the offset of these timezones to UTC (but I am open to any solution).

Date.prototype.getTimezoneOffset() seemed to be the perfect candidate, I took the example from the docs:

const myDate = new Date('August 19, 1975 23:15:30 GMT+07:00')
console.log(myDate.getTimezoneOffset())

The comment of the example states

// Expected output: your local timezone offset in minutes
// (e.g., -120). NOT the timezone offset of the date object.

I am trying to process this but I simply do not understand what Date.prototype.getTimezoneOffset() if it always returns the local offset to UTS, no matter the date it is applied to.

If the above is correct (which seems really weird, taken that getTimezoneOffset() is applied to a date object), how can I get the UTC offset of a date object?

I will ultimately use Day.js to manipulate my dates, so the final code I expected to work (but it does not per the above) was

console.log(dayjs().tz('America/Los_Angeles').toDate().getTimezoneOffset())

Solution

  • JS Dates don't contain timezone information, getTimezoneOffset() gives you the local timezone offset at a particular date:

    let myDate = new Date('August 19, 1975 23:15:30 GMT+07:00')
    console.log(myDate.getTimezoneOffset())
    
    myDate = new Date('August 19, 2023 23:15:30 GMT+03:00')
    console.log(myDate.getTimezoneOffset())
    
    /* gives for my region (timezone in the strings doesn't affect this):
    -180
    -120
    */

    Parse your date strings directly. If you want to get timezone offsets by a timezone's name:

    function getTimezoneOffset(timeZone){
      const str = new Date().toLocaleString('en', {timeZone, timeZoneName: 'longOffset'});
      const [_,h,m] = str.match(/([+-]\d+):(\d+)$/) || [, '+00', '00'];
      return h * 60 + (h > 0 ? +m : -m);
    }
    
    'America/Los_Angeles America/New_York Asia/Kolkata Pacific/Marquesas Etc/UTC'.match(/\S+/g).forEach(tz => 
      console.log(tz, getTimezoneOffset(tz))
    );

    To parse from a date string:

    function getTimezoneOffset(str){
      const [_,h,m] = str.match(/([+-]\d+):(\d+)$/) || [, '+00', '00'];
      return h * 60 + (h > 0 ? +m : -m);
    }
    
    console.log(getTimezoneOffset('August 19, 1975 23:15:30 GMT+07:00'))