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

JavascriptMomentjs

Javascript Problem Overview


I want to get current date but time should be 00:00:00.000

I've try this:

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

but I've got: 2016-01-12T23:00:00.000Z why 23 and not 00?

Javascript Solutions


Solution 1 - Javascript

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()

Solution 2 - Javascript

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);

Solution 3 - Javascript

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/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjcubicView Question on Stackoverflow
Solution 1 - JavascriptVolodymyr SynytskyiView Answer on Stackoverflow
Solution 2 - JavascriptsaikumarView Answer on Stackoverflow
Solution 3 - Javascriptuser310988View Answer on Stackoverflow