首页 > 解决方案 > toLocaleDateString 时间格式问题(Firefox 与 Chrome)

问题描述

我在 Chrome 和 Firefox 中看到此日期格式命令的不同结果:

new Date(1156550400000).toLocaleDateString('en-us', {weekday: 'long', month: 'short', day: 'numeric', hour: '2-digit', hour12: false, timeZone: 'UTC'})+'z'

在 Firefox 中,我得到了这个结果(这是所需的输出格式):

Saturday, Aug 26, 00z"

在 Chrome 中,我得到了这个结果:

"Saturday, Aug 26, 24z"

很容易检查“24”值并替换为“00”,但希望有一个内置方法......我在 toLocaleDateString 选项中是否缺少用于格式化的选项,或者获取的替代方法想要的格式?

标签: javascriptgoogle-chromedatetimefirefoxdatetime-format

解决方案


我看到选项 'hour12' 在 Mozilla Firefox 和 Google Chrome 中的工作方式不同。在这种情况下,使用选项“ hourCycle ”而不是“hour12”可能会有所帮助。

new Date(1156550400000).toLocaleDateString('en-us', {weekday: 'long', month: 'short', day: 'numeric', hour: '2-digit', hourCycle: "h23", timeZone: 'UTC'})+'z'

在 Mozilla Firefox(82.0(64 位))中,这将返回"Saturday, Aug 26, 00z". 在 Google Chrome(版本 86.0.4240.111(官方构建)(64 位))中,这将返回"Saturday, Aug 26, 00z".


推荐阅读