首页 > 解决方案 > Js计算两个日期之间的每一天

问题描述

我们认为我有以下日期:

from: 21/09/2019

to: 29/09/2019

我想要的结果是这样的:

[
  {
    "day": 21,
    "month": 9,
    "year": 2019
  },
  ...
  {
    "day": 29,
    "month": 9,
    "year": 2019
  }
]

如果我有这样的事情:

from: 21/09/2019

to: 7/10/2019

我想要的结果是这样的:

[
  {
    "day": 21,
    "month": 9,
    "year": 2019
  },
  ...
  {
    "day": 30,
    "month": 9,
    "year": 2019
  },
  ...
  {
    "day": 1,
    "month": 10,
    "year": 2019
  }
  {
    "day": 7,
    "month": 10,
    "year": 2019
  }
]

我想做的是在一个数组中打印开始日期和结束日期之间的所有天数。

我正在尝试这样的事情,但我遇到了一些问题:

let from = "23/09/2019";
let to = "7/10/2019";

function getDaysInMonth(month, year) {
  return new Date(year, month, 0).getDate();
}

function calculate(from, to) {
  let splitF = from.split("/");
  let splitT = to.split("/");
  let array = [];

  let dF = parseInt(splitF[0]);
  let dT = parseInt(splitT[0]);
  let mF = parseInt(splitF[1]);
  let mT = parseInt(splitT[1]);
  let yF = parseInt(splitF[2]);
  let yT = parseInt(splitT[2]);

  let day, init, final;

  while (true) {
    if (mF === mT && yF === yT) {
      day = dT - dF;
    } else {
      day = getDaysInMonth(mF, yF)-dF;
    }
    init = dF;
    final = init + day;
    Array.apply(null, { length: final + 1 })
      .map(Number.call, Number)
      .slice(init)
      .reduce((prev, curr) => {
        let obj = {
          day: curr,
          month: mF,
          year: yF
        };
        array.push(obj);
        return prev;
      }, []);
    if (mF === mT && yF === yT) break;
    mF++;
    dF = 1;
    if (mF === 13) {
      mF = 1;
      yF++;
    }
  }
  return array;
}

console.log(calculate(from, to));

标签: javascriptdatedate-formattingdate-parsing

解决方案


您可以将日期加 1 到开始日期,并且 Date 对象将负责验证新日期,即下个月或明年以及所有日期,重复直到结束日期toDate大于开始日期fromDate

let from = "23/09/2019";
let to = "29/10/2019";

// convert to date object by interchanging date/month expected by Date function
let fromDate = new Date(from.replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
let toDate = new Date(to.replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));

let response = [];
while(toDate > fromDate){
  response.push({day: fromDate.getDate(), month: fromDate.getMonth()+1, year: fromDate.getFullYear()});
  fromDate.setDate(fromDate.getDate()+1) // increment date by 1
}

console.log(response)


推荐阅读