Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 955
Tudor Vintilescu Avatar asked Sep 30 '13 17:09

Tudor Vintilescu


People also ask

How do you get weekday from the moment?

Syntax. moment(). weekday(Number); moment(). weekday();

How do you date the next day in a moment?

We can get tomorrow's date with the moment function and the add method. And then we can format it into a human-readable date string with the format method. to create the tomorrow variable that's set to a moment object with today's date. Then we call add with 1 and 'days' to add one day to today.

Is moment JS being deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.

How do I get current week days in JavaScript?

JavaScript - Date getDay() Method Javascript date getDay() method returns the day of the week for the specified date according to local time. The value returned by getDay() is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.


1 Answers

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

like image 153
mechanicalfish Avatar answered Sep 16 '22 11:09

mechanicalfish