Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MomentJS get the previous friday

I have a user inputted date which I convert to a moment

var newDate = moment('01/02/2015');

What I need to do is get the previous friday relative to whatever date is passed in. How can I accomplish this?

I thought about doing something like this:

moment('01/02/2015').add('-1', 'week').day(5); 

but wonder how reliable it would be.

like image 800
Ryan Mulready Avatar asked Jun 17 '15 17:06

Ryan Mulready


1 Answers

newDate.day(-2);

It's that easy. :)

day() sets the day of the week relative to the moment object it is working on. moment().day(0) always goes back to the beginning of the week. moment().day(-2)goes back two days further than the beginning of the week, i.e., last Friday.

Note: this will return to the Friday of the previous week even if newDate is on Friday or Saturday. To avoid this behavior, use this:

newDate.day(newDate.day() >= 5 ? 5 :-2);
like image 61
JayArby Avatar answered Sep 24 '22 09:09

JayArby