简体   繁体   中英

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.

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM