elzi elzi - 1 month ago 7
Javascript Question

Momentjs - Get most recent Friday

I'm trying to get the start of (12:00am, or, 00:00am) of the most recent Friday. This has been working:

moment().isoWeekday(5).startOf('day').toDate()


But it only works Friday->Sunday, on Monday morning it will then refer to the upcoming Friday, in which case this would work:

moment().add('-1', 'week').day(5).startOf('day').toDate()


but I need it be dynamic and done in one line if possible, to where I don't to perform any checks on the current day.

Is there a way to always get the most recent Friday? Regardless of what the current day is.

Edit I'm also trying to get this to return the current day (friday) if executed on a Friday.

Answer

If you don't want to use a library, it's pretty straight forward

var date = new Date();
while ( date.getDay() !== 5 ) date.setDate(date.getDate() -1);

console.log(date)

With moment

var date = moment();

var friday = date.day(date.day() >= 5 ? 5 :-2);

and if millisecond accuracy doesn't matter, you could call moment() twice to make it one line (but I would much raher use a variable)

var friday = moment().day(moment().day() >= 5 ? 5 :-2);
Comments