elzi
elzi

Reputation: 5672

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.

Upvotes: 0

Views: 1413

Answers (2)

num8er
num8er

Reputation: 19372

Check this:

var date = moment().utc().isoWeekday(5);
if(moment().day() < 5) {
  date = date.add(-1, 'week');
}

console.log('Recent friday starts:', date.startOf('day').toDate());

console.log('Recent friday ends:', date.endOf('day').toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.js"></script>

Upvotes: 0

adeneo
adeneo

Reputation: 318182

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);

Upvotes: 5

Related Questions