JavaScript-获取工作日中两个日期之间的日期

时间:2019-12-22 23:45:40

标签: javascript

我收到一个开始日期和结束日期,我想提取这两个日期之间的所有日期,但仅在指定的工作日内。

我写了一个小代码来计算日期之间“星期二,星期三和星期五”的日期:

start_date = "2019-12-31"
end_date = "2020-01-31"

它可以正常工作,但是问题是它从'Tuesday 07-01-2020'开始计算,而我想从'Tuesday 31-12-2019'开始获取日期。代码如下:

 function nextWeekdayDate(date, day_in_week) {
    var ret = new Date(date || new Date());
    ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
    return ret;
}

var delivery_dates = []

var day_num = { "Mon": 1, "Tue": 2, "Wed": 3, "Thu": 4, "Fri": 5 };
var days_of_week = ["Tue", "Wed", "Fri"];

start_date = new Date('2019-12-31');
end_date = new Date('2020-01-31');

var new_dates = []
 while (start_date < end_date) {
  for (var i = 0; i <= 2; i++) {
    start_date = nextWeekdayDate(start_date, day_num[days_of_week[i]]);
    delivery_dates.push(start_date)
  }
}
console.log(delivery_dates);

任何想法我的代码有什么问题吗?这是一个jsfiddle: https://jsfiddle.net/mpe49hun/8/

1 个答案:

答案 0 :(得分:1)

由于第一个日期是星期二,因此该函数

function nextWeekdayDate(date, day_in_week) {
    var ret = new Date(date || new Date());
    ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
    return ret;
}

ret添加为零应为七天

将“数学”更改为ret.setDate(ret.getDate() + ((7 + day_in_week - ret.getDay())) % 7);将解决此问题

function nextWeekdayDate(date, day_in_week) {
  var ret = new Date(date || new Date());
  ret.setDate(ret.getDate() + ((7 + day_in_week - ret.getDay())) % 7);
  return ret;
}
var delivery_dates = []

var day_num = {
  "Mon": 1,
  "Tue": 2,
  "Wed": 3,
  "Thu": 4,
  "Fri": 5
};
var days_of_week = ["Tue", "Wed", "Fri"];

start_date = new Date('2019-12-31');
end_date = new Date('2020-01-31');

var new_dates = []
while (start_date < end_date) {
  for (var i = 0; i <= 2; i++) {
    start_date = nextWeekdayDate(start_date, day_num[days_of_week[i]]);
    delivery_dates.push(start_date)
  }
}
console.log(delivery_dates);


但是,例如,给定开始日期为2019-12-25,则输出中将不包括星期三25/12和星期五27/12-如果应将其包括在内,则以下代码可能是你想要

var delivery_dates = []

var day_num = { "Mon": 1, "Tue": 2, "Wed": 3, "Thu": 4, "Fri": 5 };
var days_of_week = ["Tue", "Wed", "Fri"];
var includedDays = days_of_week.map(d => day_num[d]);


start_date = new Date('2019-12-25');
end_date = new Date('2020-01-31');

while (start_date <= end_date) {
    if (includedDays.includes(start_date.getDay())) {
        delivery_dates.push(new Date(start_date));
    }
    start_date.setDate(start_date.getDate() + 1);
}
console.log(delivery_dates)