【问题标题】:How can I calculate the hours of difference between two timezones in nodeJS?如何计算nodeJS中两个时区之间的差异小时数?
【发布时间】:2021-11-18 19:54:08
【问题描述】:

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

类似

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

冬天和夏天的时间交替,我不能简单地使用 1 小时! :(

【问题讨论】:

  • 哪个日期和时间的偏移量?由于Europe/Amsterdam 使用夏令时,UTC 偏移量并不总是相同。
  • 这正是我的问题所在!否则我本可以在课程顶部添加固定差异。

标签: javascript node.js date


【解决方案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)}`));

【讨论】:

    【解决方案2】:

    我最终做的并且对我来说完美的事情是以下

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 1970-01-01
      • 2020-05-13
      相关资源
      最近更新 更多