Michael Murata Michael Murata - 2 months ago 5
Javascript Question

Moment() vs predefined Moment() date

I am a bit confused on how the Moment functions work (such as

startOf()
,
weekday()
, etc).

My question is: how do I obtain the start of the week from a predefined date?

Consider these two calls on
9/21/16
:

moment().startOf('week') // Returns a moment object with date set to Sun Sep 18 2016 ...


vs

moment(new Date("9/21/16")).startOf('week') // Returns a moment object with date set to Wed Sep 21 2016 ...


Why don't these behave in the same way? The same is true when using
weekday(0)
instead of
startOf('week')

Answer

How do you know that moment(new Date("9/21/16")).startOf('week') is returning Wed Sep 21 2016? Are you looking inside the returned object? If so, I think you're just seeing the input date. You should use moment.format() function to get the actual date:

// "September 18, 2016"
moment().startOf("week").format("LL");

// "September 18, 2016"
moment("9/21/16", "MM/DD/YY").startOf("week").format("LL");

// "September 18, 2016" on my system (not recommended)
moment(new Date("9/21/16")).startOf("week").format("LL");
Comments