使用JavaScript获取两个日期之间的日期列表

6

在JavaScript中,有没有一种方法可以从MySQL格式的两个日期中获取日期列表。我不想使用任何库来完成这个任务。以下是我所做的内容:

function generateDateList(from, to) {

    var getDate = function(date) { //Mysql Format
        var m = date.getMonth(), d = date.getDate();
        return date.getFullYear() + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
    }
    var fs = from.split('-'), startDate = new Date(fs[0], fs[1], fs[2]), result = [getDate(startDate)], start = startDate.getTime(), ts, end;

    if ( typeof to == 'undefined') {
        end = new Date().getTime();
    } else {
        ts = to.split('-');
        end = new Date(ts[0], ts[1], ts[2]).getTime();
    }
    while (start < end) {
        start += 86400000;
        startDate.setTime(start);
        result.push(getDate(startDate));
    }
    return result;
}

console.log(generateDateList('2014-2-27', '2014-3-2'));

我在Chrome和Node.js中进行了测试,以下是结果。

[ '2014-02-27',
  '2014-02-28',
  '2014-02-29',
  '2014-02-30',
  '2014-02-31',
  '2014-03-01',
  '2014-03-02' ]

这是一个闰年:-D...,我该如何解决这个问题?或者有没有更好的方法?

6
JavaScript 日期中的月份是从0开始编号的。月份“02”代表的是三月,而不是二月。 - Pointy
这解决了我的问题。谢谢@Pointy。 - Oshan Wisumperuma
7个回答

13
const listDate = [];
const startDate ='2017-02-01';
const endDate = '2017-02-10';
const dateMove = new Date(startDate);
let strDate = startDate;

while (strDate < endDate) {
  strDate = dateMove.toISOString().slice(0, 10);
  listDate.push(strDate);
  dateMove.setDate(dateMove.getDate() + 1);
};

2
请添加更多关于您的回答的描述和/或信息,以及它如何解决所提出的问题,以便其他人可以轻松理解,无需询问澄清。 - koceeng
优秀的答案。 - Samrat Saha

3

从开始日期开始,每次增加一天,直到达到结束日期。

注意:MySQL日期是标准格式,无需手动解析,只需将其传递给Date构造函数:new Date('2008-06-13')

const addDays = (date, days = 1) => {
  const result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
};

const dateRange = (start, end, range = []) => {
  if (start > end) return range;
  const next = addDays(start, 1);
  return dateRange(next, end, [...range, start]);
};

const range = dateRange(new Date("2014-02-27"), new Date("2014-03-02"));

console.log(range);
console.log(range.map(date => date.toISOString().slice(0, 10)))

在这里我使用了递归函数,但你也可以使用while循环来实现相同的功能(请参见其他答案)。


3
我使用了这个来自https://flaviocopes.com/how-to-get-days-between-dates-javascript/的方法。
const getDatesBetweenDates = (startDate, endDate) => {
  let dates = []
  //to avoid modifying the original date
  const theDate = new Date(startDate)
  while (theDate < new Date(endDate)) {
    dates = [...dates, new Date(theDate)]
    theDate.setDate(theDate.getDate() + 1)
  }
  dates = [...dates, new Date(endDate)]
  return dates
}

请按以下方式调用该函数:

getDatesBetweenDates("2021-12-28", "2021-03-01")

注意 - 我只需修复 while 循环和日期数组中的 Date 对象创建问题 (new Date())。除此之外,代码与上面链接中的代码几乎一样。


0
dateRange(startDate, endDate) {
    var start      = startDate.split('-');
    var end        = endDate.split('-');
    var startYear  = parseInt(start[0]);
    var endYear    = parseInt(end[0]);
    var dates      = [];

    for(var i = startYear; i <= endYear; i++) {
      var endMonth = i != endYear ? 11 : parseInt(end[1]) - 1;
      var startMon = i === startYear ? parseInt(start[1])-1 : 0;
      for(var j = startMon; j <= endMonth; j = j > 12 ? j % 12 || 11 : j+1) {
        var month = j+1;
        var displayMonth = month < 10 ? '0'+month : month;
        dates.push([i, displayMonth, '01'].join('-'));
      }
    }
    return dates;
  }

0

我扩展了Công Thắng的杰出答案,以返回{年,月,日},认为值得分享:

function getDates(startDate, endDate) {
  const days = [],  
        months = new Set(),
        years = new Set()

  const dateMove = new Date(startDate)
  let date = startDate

  while (date < endDate){
    date = dateMove.toISOString().slice(0,10)
    months.add(date.slice(0, 7))
    years.add(date.slice(0, 4))
    days.push(date)
    dateMove.setDate(dateMove.getDate()+1) // increment day
  }
  return {years: [...years], months: [...months], days} // return arrays
}

console.log(getDates('2016-02-28', '2016-03-01')) // leap year
/* =>
 {
    years: [ '2016' ],
    months: [ '2016-02', '2016-03' ],
    days: [ '2016-02-28', '2016-02-29', '2016-03-01' ]
  }
*/
const {months} = getDates('2016-02-28', '2016-03-01') // get only months

基本上,该函数只是从开始到结束将内置的日期对象增加一天,而集合则捕获唯一的月份和年份。


0
var oDate1 = oEvent.getParameter("from"),
    oDate2 = oEvent.getParameter("to");

        var aDates = [];
        var currentDate = oDate1;
        while (currentDate <= oDate2) {
            aDates.push(new Date(currentDate));
            currentDate.setDate(currentDate.getDate() + 1);
        }

欢迎来到StackOverflow。请尽量清晰地解释为什么这是问题的答案。 - Jeroen Heier
在这个网站上,仅提供代码的答案通常不被看好。您能否编辑您的答案并包含一些注释或解释您的代码?解释应该回答以下问题:它是做什么的?它是如何做到的?它去哪里?它是如何解决 OP 的问题的?请参阅:如何回答问题。谢谢! - Eduardo Baitello

0
如果您的起始日期和结束日期之间有很大的间隔,那么使用 moment 可能是至关重要的。
var moment = require('moment');

function getDates(fromDate, toDate) {
  const dateArray = [];
  let currentDate = moment(fromDate);
  const endDate = moment(toDate);
  while (currentDate <= endDate) {
    dateArray.push({
      date: moment(currentDate).format('YYYY-MM-DD'),
      month: moment(currentDate).month(),
      day: moment(currentDate).day(),
    });
    currentDate = moment(currentDate).add(1, 'days');
  }
  return dateArray;
}

console.log(getDates(new Date('2018-01-01'), new Date('2028-07-01')));

输出:

[
  { date: '2018-01-01', month: 0, day: 1 },
  { date: '2018-01-02', month: 0, day: 2 },
  { date: '2018-01-03', month: 0, day: 3 },
  { date: '2018-01-04', month: 0, day: 4 },
  { date: '2018-01-05', month: 0, day: 5 },
  { date: '2018-01-06', month: 0, day: 6 },
  { date: '2018-01-07', month: 0, day: 0 },
  { date: '2018-01-08', month: 0, day: 1 },
  ... 3765 more items
]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接