简体   繁体   English

Momentjs-获取最近的星期五

[英]Momentjs - Get most recent Friday

I'm trying to get the start of (12:00am, or, 00:00am) of the most recent Friday. 我正在尝试开始最近一个星期五的(12:00 am,或00:00 am)。 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) 如果毫秒精度无关紧要,则可以调用moment()两次使其变为一行(但我会更愿意使用一个变量)

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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