我正在尝试创建一个函数,返回特定工作日的日期(最后一次发生的时间)。
例如,今天是星期二,2016-08-16。如果我要查找上周五,它应该返回 2016-08-12。
目前,我使用的代码是为特定工作日编写的。我如何更改它以使其返回我要求的任何工作日的日期?
let t = new Date().getDate() + (6 - new Date().getDay() - 1) - 7;
let d = new Date();
d.setDate(t);
最佳答案
var WEEK_DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var MILLIS_PER_DAY = 86400000;
function lastOccurrenceOf(weekDay) {
var desiredIndex = WEEK_DAYS.indexOf(weekDay);
var currentDate = new Date;
var daysDifference = (currentDate.getDay() - desiredIndex + 6) % 7 + 1; //the number of days ago
return new Date(currentDate.getTime() - MILLIS_PER_DAY * daysDifference);
}
console.log(lastOccurrenceOf('Tuesday').toString());
console.log(lastOccurrenceOf('Friday').toString());
关于javascript - 动态获取特定工作日最后一次出现的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38985211/