首页 > 解决方案 > moment.utc(date) 和 moment(date).utc() 之间的区别

问题描述

试图了解以下行为和区别:

moment.utc(date) and moment(date).utc()

使用 '2018-05-31' 作为参数:

moment.utc('2018-05-31').format()会给:

‌2018-05-31T00:00:00Z

同时moment('2018-05-31').utc().format()会给出:

2018-05-31T04:00:00Z

我在 EST 时区执行两者。

标签: javascriptmomentjsutc

解决方案


第一个moment.utc(String)将您的字符串解析为 UTC,而后者您的时刻实例转换为 UTC 模式。

默认情况下,moment 解析并以本地时间显示。

如果要解析或显示 UTC 时刻,可以使用moment.utc()代替moment().

这给我们带来了 Moment.js 的一个有趣的特性。UTC 模式。

请参阅Local vs UTC vs Offset指南以了解有关 UTC 模式和本地模式的更多信息。

console.log( moment.utc('2018-05-31').format() );
console.log( moment('2018-05-31').utc().format() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>


推荐阅读