繁体   English   中英

如何计算 nodeJS 中两个时区之间的时差?

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

如何计算 UTC(我用 new Date() 生成的)和欧洲标准时间之间的差异?

就像是

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

我不能简单地使用 1 小时,因为冬季和夏季的时间转换: :(

您可以使用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)}`));

我最终最终做了什么,对我来说完美的是以下

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

这将返回阿姆斯特丹领先于 UTC 的小时数。

对于正在寻找使用 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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