Tudor Vintilescu Tudor Vintilescu - 1 month ago 7
Javascript Question

Moment js getting next date given specified week day

I seem to have a bit of a problem getting the previous Monday given a particular date. I'm trying to use Moment js for the task. Obviously, I can do it by hand, but found it curious that I couldn't get it to work using the example in the moment.js documentation on their website: http://momentjs.com/docs/#/get-set/day/.

I was trying something like:

moment([2013, 08, 15, 15, 20]).day(-1).format('ddd, MMM DD')


which results in the 'two days ago' date, that being September 13 instead of the expected September 9th.

Does anybody have a clue here? Thanks.

Answer

Here is how it works:

moment().day(1) // this monday
moment().day(-6) // last monday, think of it as this monday - 7 days = 1 - 7 = -6

Same applies in other direction:

moment().day(8) // next monday, or this monday + 7 days = 1 + 7 = 8

Your code moment().day(-1) can be explained as this Sunday - 1 day = 0 - 1 = -1 or this Saturday - 7 days = 6 - 7 = -1

Comments