将不带时区的日期字符串转换为特定时区时刻对象



在我的应用程序后端应用用户时区并将格式化日期发送到UI。但是当我将该字符串转换为日期对象时。它正在转换为用户的系统时区。如何将日期字符串更改为特定时区的时刻对象而不是用户系统时区。

我正在使用即时时区库。

例如,07/26/2022 07:01:14 AM已经在GMT-5,但当我使用moment(new Date(dateString))将其转换为时刻对象时,它正在将其转换成用户系统时区。

我如何将其转换为用户定义的时区,即GMT-5

我只是把它搞起来了——没有使用momentjs,因为它不再维护

const input = "07/26/2022 07:01:14 AM"
const date= new Date(input);
//                                                             VVVVVV timezone fix
date.setMinutes(date.getMinutes() - date.getTimezoneOffset() + 5 * 60);
// date is now "07/26/2022 07:01:14 AM GMT-5"
// the following is just to show it's right
const verifyDate = new Intl.DateTimeFormat(navigator.language, {
dateStyle: 'full',
timeStyle: 'full',
timeZone: 'America/Bogota' // just picking a GMT-5 zone at random
}).format(date);
console.log(verifyDate)
// at this point

最新更新