Javascript:获取当前星期的错误日期

时间:2020-04-15 05:45:33

标签: javascript

我想获取当前一周的所有七个日期(星期一至星期日)。下面的代码运行良好。

let curr = new Date(); // today's date is: 15th April 2020
let week = []
for (let i = 1; i <= 7; i++) {
    let first = curr.getDate() - curr.getDay() + i;
    let day = new Date(curr.setDate(first)).toISOString().slice(0, 10)
    week.push(day);
}
console.log(week); // output: ["2020-04-13", "2020-04-14", "2020-04-15", "2020-04-16", "2020-04-17", "2020-04-18", "2020-04-19"]

但是,假设当前日期是2020年4月19日。那么代码将返回错误的日期。

let curr = new Date('2020-04-19'); // today's date is: 19th April 2020
let week = []
for (let i = 1; i <= 7; i++) {
 let first = curr.getDate() - curr.getDay() + i;
 let day = new Date(curr.setDate(first)).toISOString().slice(0, 10)
    week.push(day);
 }
console.log(week); // output: ["2020-04-20", "2020-04-21", "2020-04-22", "2020-04-23", "2020-04-24", "2020-04-25", "2020-04-26"]

它应该返回如下输出 ["2020-04-13", "2020-04-14", "2020-04-15", "2020-04-16", "2020-04-17", "2020-04-18", "2020-04-19"]

3 个答案:

答案 0 :(得分:1)

由于getDay()在星期日返回0,但是您的代码需要7才能找到前面的星期一,因此您只需要允许它并在需要时进行调整即可:

let curr = new Date('2020-04-19'); // today's date is: 19th April 2020
let week = []
for (let i = 1; i <= 7; i++) {
  let dow = curr.getDay();
  if (!dow) dow = 7;
  let first = curr.getDate() - dow + i;
  let day = new Date(curr.setDate(first)).toISOString().slice(0, 10)
  week.push(day);
}
console.log(week);

答案 1 :(得分:1)

如果curr落在星期日,您想跳回整整一周,所以我要更改此行:

let first = curr.getDate() - curr.getDay() + i;

收件人:

let first = curr.getDate() - ( curr.getDay() ? curr.getDay() : 7 ) + i;

答案 2 :(得分:-1)

相关问题