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! :(
CodePudding user response:
You can get the offset for a particular location for any date using Intl.DateTimeFormat with suitable options, e.g.
/* @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)}`));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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.