如何使用 moment.js 设置 00:00:00

How to set 00:00:00 using moment.js

我想获取当前日期,但时间应该是 00:00:00.000

我试过这个:

var m = moment();
m.set({hour:0,minute:0,second:0,millisecond:0});
console.log(m.toISOString());

但我得到了:2016-01-12T23:00:00.000Z为什么是 23 而不是 00?

var time = moment().toDate();  // This will return a copy of the Date that the moment uses

time.setHours(0);
time.setMinutes(0);
time.setSeconds(0);
time.setMilliseconds(0);

您没有展示如何创建字符串 2016-01-12T23:00:00.000Z,但我假设通过 .format()

无论如何,.set() 使用的是您当地的时区,但时间字符串中的 Z 表示 zero time,也称为 UTC。

https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators

所以我假设你当地的时区比 UTC 晚 23 小时?

展示了如何加载 UTC 时间,但另一种选择是使用 .format() 调用,该调用使用本地时区而不是 UTC 输出。

http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/

Moment.js 将日期存储为 utc 并且可以对其应用不同的时区。默认情况下,它应用您当地的时区。 如果您想在 utc 日期时间上设置时间,您需要指定 utc 时区。

试试下面的代码:

var m = moment().utcOffset(0);
m.set({hour:0,minute:0,second:0,millisecond:0})
m.toISOString()
m.format()