MomentJS get previous friday

I have a user entered date that I am converting in an instant

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

      

What I need to do is get the previous Friday in relation to any transfer date. How can i do this?

I thought about doing something like this:

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

      

but ask yourself how reliable it is.

+3


source to share


1 answer


newDate.day(-2);

      

It is so simple.:)

day()

sets the day of the week relative to the moment at which it operates. moment().day(0)

always returns to the beginning of the week. moment().day(-2)

returns two days further than at the beginning of the week, i.e. last Friday.



Note: this will revert back 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);

      

+11


source







All Articles