Reputation: 604
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.
Upvotes: 12
Views: 7340
Reputation: 859
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);
Upvotes: 25