javascript - 如何在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 。
解决方案
正确的解决方案是将这些缩写映射到 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()
改为。
推荐阅读
- google-bigquery - 我们可以绕过 BigQuery 数据连接器 10000 行的限制吗?
- c++ - Why is a re-constructed map type different from the original one?
- python - DJANGO virtual env unable to import models when running a standalone script
- typescript - 在打字稿中使用量角器引用静态文件进行测试
- spring-boot - Is there a JSON schema or data model for Spring Boot Actuator REST interfaces?
- asp.net-core - ASP.NET Core Windows 身份验证从 UI 网站传递到 API
- java - Android 应用程序在手机上运行,但在平板电脑上无法运行
- javascript - 如何过滤图像表
- visual-studio - 如何在 SSRS 中创建一个子组,将其他组的特定行的值相加?
- javascript - _app.js 类组件 Next.js 中的上下文 API 调度(消费者)