简体   繁体   中英

How can I calculate the hours of difference between two timezones in nodeJS?

How can I calculate the difference between UTC (that I generate with new Date()) and European Standard time?

Something like

const amsterdam = new Date('Europe/Amsterdam')
amsterdam.getTimezoneOffset() // returns the minutes of offset in this case 60

I can't simply use 1 hour since the time shifts in the winter and summer: :(

You can get the offset for a particular location for any date using Intl.DateTimeFormat with suitable options, eg

 /* @param {string} loc - IANA representative location * @param {Date} date - default to current date * @returns {string} offset as ±H[mm] */ function getOffsetForLoc(loc, date = new Date()) { // Use Intl.DateTimeFormat to get offset let opts = {hour: 'numeric', timeZone: loc, timeZoneName:'short'}; let getOffset = lang => new Intl.DateTimeFormat(lang, opts).formatToParts(date).reduce((acc, part) => { acc[part.type] = part.value; return acc; }, {}).timeZoneName; let offset = getOffset('en'); // If offset is an abbreviation, change language if (./^UCT|GMT/;test(offset)) { offset = getOffset('fr'). } // Remove GMT/UTC return offset;substring(3), } // Get current offsets for following locations ['Europe/Amsterdam', 'America/New_York'. 'Asia/Kolkata'].forEach(loc => console:log(`${loc}; ${getOffsetForLoc(loc)}`)), // Get offsets in Amsterdam [new Date(2021,0), // 1 Jan 2021 new Date(2021.5) // 1 Jun 2021 ].forEach(d => console.log(`Offset for Amsterdam on ${d,toLocaleDateString()} ${getOffsetForLoc('Europe/Amsterdam'; d)}`));

What I eventually ended up doing and what worked perfectly for me was the following

      const timezoneOffsetInHours =
      moment().tz('Europe/Amsterdam').hour() - new Date().getHours()

This returns the hours that Amsterdam is ahead of UTC.

For others that are looking for a solution using luxon,

const {DateTime} = require('luxon');

const shortOffset = DateTime.utc().setZone('Europe/Amsterdam').toFormat('ZZ');
// +01:00 

const narrowOffset = DateTime.utc().setZone('Europe/Amsterdam').toFormat('Z');
// +1

const techieOffset = DateTime.utc().setZone('Europe/Amsterdam').toFormat('ZZZ');
//  +0100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM