首页 > 解决方案 > Firefox 浏览器上带有时区错误的 JavaScript 日期对象

问题描述

我需要使用时区 CST/CDT 创建 javascript 对象,下面的代码行在 chrome 中工作正常,但在 firefox 上没有

new Date("2020-06-06 05:37:34.0" + ' CST/CDT');

镀铬结果:

Sat Jun 06 2020 15:37:34 GMT+0500 (Pakistan Standard Time)

火狐结果:

Invalid Date

需要建议来解决它。

标签: javascriptgoogle-chromedatefirefox

解决方案


始终尝试使用 UTC 日期,这意味着将 Dates 存储和执行计算为UTC

如果要创建特定于时区的 Date 对象,请执行以下操作,我已经展示了如何将其转换回 UTC/本地时区:

const date = new Date('2010-05-11T10:11:00-0500');//CDT time
console.log(date.toString()); //date as per the current timezone of the machine this code is executed => "Tue May 11 2010 20:41:00 GMT+0530 (India Standard Time)"
console.log(date.toISOString());//converts the Date as UTC based ISO date string => "2010-05-11T15:11:00.000Z"

推荐阅读