首页 > 解决方案 > Momenjs 格式化程序将时间从 00 更改为 03 小时

问题描述

为什么moment("2020-08-26T00:00:00Z").format('DD.MM.YYYY HH:mm:ss Z')给出“26.08.2020 03:00:00 +03:00”。我确实了解当前时区的添加,但为什么时间也会改变?

jsbin 示例在这里

标签: javascriptmomentjs

解决方案


在 ISO 8601 格式中,末尾的“Z”指的是 UTC+0 时区2020-08-26T00:00:00Z因此与 相同2020-08-26T00:00:00+00:00

如果要在构造函数中使用另一个时区,请显式指定它:

moment('2020-08-26T00:00:00+03:00').format('DD.MM.YYYY HH:mm:ss Z')
//                         ^^^^^^
// if the user agent's timezone is UTC+3,
// this will be formatted as "26.08.2020 00:00:00 +03:00"

另一方面,如果您想构建一个 UTC+0 日期时间并将其格式化为 UTC+0,忽略用户代理的 timezone,请使用它(根据您的评论):

moment("2020-08-26T00:00:00Z").utc().format("DD.MM.YYYY HH:mm:ss Z")
//                            ^^^^^^
// this will _always_ be formatted as "26.08.2020 00:00:00 +00:00"

推荐阅读