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

时间:2014-10-02 15:14:16

标签: javascript node.js

从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测试它,下面的nodejs是结果。

[ '2014-02-27',
  '2014-02-28',
  '2014-02-29',
  '2014-02-30',
  '2014-02-31',
  '2014-03-01',
  '2014-03-02' ]
大闰年:-D ......,我怎么能解决这个问题?还是有更好的方法。?

6 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分: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;
  }

答案 2 :(得分: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);
        }

答案 3 :(得分:0)

采用开始日期并将其增加一天,直到达到结束日期。

  

注意: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)))

这里我使用了递归函数,但是您可以使用一会儿实现相同的目的(请参见其他答案)。

答案 4 :(得分:0)

我扩展了贡(CôngThắ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

基本上,该函数仅将内置Date对象从开始到结束增加一天,而Sets则捕获唯一的月份和年份。

答案 5 :(得分:0)

我使用了来自 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循环和dates数组中解决Date对象创建(新Date())的问题。除此之外,代码与上述链接中的代码几乎相同