如何計算 UTC(我使用 new Date() 生成)和歐洲標準時間之間的差異?
就像是
const amsterdam = new Date('Europe/Amsterdam')
amsterdam.getTimezoneOffset() // returns the minutes of offset in this case 60
我不能簡單地使用1小時,因為冬天和夏天的時間變化!:(
uj5u.com熱心網友回復:
您可以使用具有合適選項的Intl.DateTimeFormat獲取任何日期的特定位置的偏移量,例如
/* @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)}`));
uj5u.com熱心網友回復:
我最終做了什么,對我來說完美的是以下內容
const timezoneOffsetInHours =
moment().tz('Europe/Amsterdam').hour() - new Date().getHours()
這將回傳阿姆斯特丹早于 UTC 的小時數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362341.html
標籤:javascript 节点.js 日期
上一篇:計算連續日期R
