如何将带有 3 个字母时区缩写的日期转换为 Javascript 中的 UTC?

How to convert dates with 3 letter timezone abbreviation, to UTC, in Javascript?

我需要将日期时间从我无法更改的输入格式(此:"Tue, 30 Jul 2019 21:15:53 GMT")转换为 UTC,格式为 Javascript。

我实际上需要获取这些日期作为自 Unix 纪元(1970 年)以来的毫秒数,但获取 UTC 将是一个开始。

有没有办法轻松做到这一点?如果需要,我可以使用第三方库。我听说过 moment-timezone.js 但不清楚如何解析 3 个字母的时区,即这些:https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations.

如果要将日期转换为 UTC 格式,可以使用 toISOString()

new Date('Tue, 30 Jul 2019 21:15:53 GMT').toISOString()

有关更多信息,请查看此 reference

此外,要将日期转换为毫秒,您可以使用 Date.UTC()

Date.UTC(year[, month[, day[, hour[, minute[, second[, millisecond]]]]]])

reference

示例:

utcMillisecond = (e) => {
    const regex = /(T)|(:)|(-)/g;
    const utc = new Date(e).toISOString().slice(0, 19).replace(regex, ' ').split(' ');
    const utcMillisecond = Date.UTC(utc[0], utc[1], utc[2], utc[3], utc[4])
    return utcMillisecond
}

utcMillisecond("Tue, 30 Jul 2019 21:15:53 GMT")
//1567199700000

正确的解决方案是将这些缩写映射到与 GMT 的偏移量的库。 moment-timezone, nor date-fns-tz, nor luxon, nor timezone-support do this, but timezone-abbr-offsets does and is very minimalistic.

都没有

幸运的是,new Date() 可以解析你的格式减去时区,所以我们将把它分开并计算偏移量:

import timezones from 'timezone-abbr-offsets';

function abbrTzToUtc(dateString) {
  // Get the date and the timezone from the input string
  let [, date, tz] = dateString.match(/^(.*)\s+(\w+)$/);
  // Ignore the timezone and parse the date as GMT
  date = new Date(date + 'Z');
  // Add the offset caused by the original timezone
  date = new Date(date.getTime() + timezones[tz] * 60 * 1000);
  return date;
}

console.log(abbrTzToUtc('Tue, 30 Jul 2019 21:15:53 MET'));

作为测试,上面的代码应该 return 2019-07-30T22:15:53.000Z.

如果您想要自 Unix 纪元以来的毫秒数,请改为 return date.getTime()