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

我想得到当前的日期,但时间应该是 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?

197811 次浏览
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);

You've not shown how you're creating the string 2016-01-12T23:00:00.000Z, but I assume via .format().

Anyway, .set() is using your local time zone, but the Z in the time string indicates zero time, otherwise known as UTC.

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

So I assume your local timezone is 23 hours from UTC?

saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format() call that outputs using your local timezone, rather than UTC.

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

Moment.js stores dates it utc and can apply different timezones to it. By default it applies your local timezone. If you want to set time on utc date time you need to specify utc timezone.

Try the following code:

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