首页 > 解决方案 > 如何在Javascript中将带有3个字母时区缩写的日期转换为UTC?

问题描述

我需要使用 Javascript 将日期时间从我无法更改的输入格式(本:“星期二,2019 年 7 月 30 日 21:15:53 GMT”)转换为 UTC。

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

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

标签: javascriptdatetimedatetime-format

解决方案


正确的解决方案是将这些缩写映射到 GMT 偏移量的库。既不moment-timezone是,也不是date-fns-tz,也不是luxon,也不timezone-support是这个,但是timezone-abbr-offsets确实并且非常简约

幸运的是,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'));

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

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


推荐阅读