动态获取特定工作日最后一次出现的日期 [英] Get date of last occurrence of a specific weekday dynamically

查看:42
本文介绍了动态获取特定工作日最后一次出现的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数返回特定工作日的日期,即上次发生的时间.

I'm trying to create a function that returns the date of a specific weekday, the last time it occurred.

例如,今天是2016年8月16日,星期二.如果我正在寻找上周五,它将返回2016-08-12.

For example, today it's Tuesday, 2016-08-16. If I was looking for last Friday, it should return 2016-08-12.

当前,我使用的代码是为特定工作日编写的.我该如何更改它以使其返回我要求的工作日的日期?

Currently, the code I'm using is written for a specific weekday. How could I change this to make it return the date of whatever weekday I'm asking for?

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

这篇关于动态获取特定工作日最后一次出现的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆