使用矩根据时区将字符串日期和时间转换为utc

问题描述

使用nodejs服务器中的矩将本地时间从前端转换为utc。

我的时间格式为date = '10-07-2020 08:45 PM'(字符串格式)。当我使用moment(date).format()时,其转换格式为此2020-10-07 20:45:00+05:30时区是基于服务器添加的,而我有timezone = '+4:00'这是我的本地时区。我想基于timezone字段而不是基于服务器时区将日期字符串转换为UTC。我该怎么办?

我尝试了以下方法,但没有找到合适的解决方案

moment.utc(moment(date).utcOffset(timezone)).format('YYYY-MM-DD HH:mm:ss')

任何人请提出建议

解决方法

您可以使用moment-timezone根据字符串和特定时区创建日期。为此,您需要指定格式和相应的时区。像这样:

const date = moment.tz("10-07-2020 08:45 pm","M-D-YYYY hh:mm a","Europe/Samara");
console.log(date.toISOString());
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>

,

也许暂时不要使用intl DateTimeFormat

有一些可能性

const options = { weekday: 'long',year: 'numeric',month: 'long',day: 'numeric',hour: 'numeric',minute: 'numeric',second: 'numeric',};

const date = new Date('10-07-2020 08:45 PM')
console.log(date)


options.timeZone = 'Europe/Ulyanovsk';
options.timeZoneName = 'short';
console.log(new Intl.DateTimeFormat('en-US',options).format(date));

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...