JavaScript:获取两个日期之间的所有月份?

时间:2015-05-26 16:57:04

标签: javascript

我有两个这样的日期字符串:

onActivityResult()

我想最终得到一个像这样的字符串数组:

var startDate = '2012-04-01';
var endDate = '2014-11-01';

到目前为止,这是我所拥有的,但它非常难看:

var dates = ['2012-04-01', '2012-05-01', '2012-06-01' .... '2014-11-01',];

有更好的方法吗? JSFiddle

10 个答案:

答案 0 :(得分:13)

这应该产生所需的输出:

function 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;
}

只需使用您现有的日期格式调用它:

dateRange('2013-11-01', '2014-06-01')
// ["2013-11-01", "2013-12-01", "2014-01-01", "2014-02-01", "2014-03-01", "2014-04-01", "2014-05-01", "2014-06-01", "2014-07-01", "2014-08-01", "2014-09-01", "2014-10-01", "2014-11-01", "2014-12-01"]

答案 1 :(得分:13)

你也可以使用优秀的moment.js库:

var startDate = moment('2012-04-01');
var endDate = moment('2014-11-01');

var result = [];

if (endDate.isBefore(startDate)) {
    throw "End date must be greated than start date."
}      

while (startDate.isBefore(endDate)) {
    result.push(startDate.format("YYYY-MM-01"));
    startDate.add(1, 'month');
}

JSFiddle

答案 2 :(得分:3)

如果加载额外的库不是问题,你总是可以试试真棒MomentJS 给予非常干净和强大的日期操作。

var startDate = moment('2012-04-01');
var endDate = moment('2014-11-01');

var dates = [];
endDate.subtract(1, "month"); //Substract one month to exclude endDate itself

var month = moment(startDate); //clone the startDate
while( month < endDate ) {
    month.add(1, "month");
    dates.push(month.format('YYYY-MM-DD'));
}

console.log(dates);

JSFiddle here

答案 3 :(得分:2)

您正在处理“逻辑”跳跃,因此您实际上并不需要定时关节炎。所以这是一个简单的计数问题:

var startDate = '2012-04-01';
var endDate = '2014-11-01';
var dates = [];

var d0 = startDate.split('-');
var d1 = endDate.split('-');

for (
    var y = d0[0];
    y <= d1[0];
    y++
) {
    for (
        var m = d0[1];
        m <= 12;
        m++
    ) {
        dates.push(y+"-"+m+"-1");
        if (y >= d1[0] && m >= d1[1]) break;
    };
    d0[1] = 1;
};

console.log(dates);

答案 4 :(得分:1)

以上所有解决方案都以O(n ^ 2)时间复杂度运行,效率不是很高。 请参见以下O(n)时间复杂度的解决方案:

function getAllMonths(start, end){	
	let startDate = new Date(start);
	let startYear = startDate.getFullYear();
	let startMonth = startDate.getMonth()+1;
	
	let endDate = new Date(end);
	let endYear = endDate.getFullYear();
	let endMonth = endDate.getMonth()+1;
	
	let countMonth = 0;
	let countYear = 0;
	let finalResult = [];

	for(let a=startYear; a<=endYear; a++){

		if(startYear<endYear){
			if(countYear==0){
				countMonth += 12-startMonth;
            }else 
			if(countYear>0){
				countMonth += 12;
            }
			countYear+=1;
			startYear++;
        }else 
		if(startYear==endYear){
			countMonth+=endMonth;
        }
    }
	for(let i=startMonth; i<=countMonth+startMonth; i++){
		finalResult.push(startDate.getFullYear()+(Math.floor(i/12)) + "-" + Math.round(i%13) + "-" + "01");
    }
	return finalResult;
}

getAllMonths('2016-04-01', '2018-01-01');

可能共享更简单的代码

答案 5 :(得分:1)

  const getMonths = (fromDate, toDate) => {
    const fromYear = fromDate.getFullYear();
    const fromMonth = fromDate.getMonth();
    const toYear = toDate.getFullYear();
    const toMonth = toDate.getMonth();
    const months = [];
    for(let year = fromYear; year <= toYear; year++) {
      let month = year === fromYear ? fromMonth : 0;
      const monthLimit = year === toYear ? toMonth : 11;
      for(; month <= monthLimit; month++) {
        months.push({ year, month })
      }
    }
    return months;
  }
const sample = getMonths(new Date('2022-07-28'), new Date('2023-03-20'));
console.log(sample);
document.write('check the console output');

https://jsfiddle.net/xfayoqvs/

答案 6 :(得分:0)

仍然不是一个非常优雅的答案,但到达你想要的字符串数组:

{{1}}

jsfiddle链接:the one in the docs

答案 7 :(得分:0)

在给定日期和现在使用moment.js之间获得所有月份的所有头几天的示例。

   var getMonths = function (startDate) {
    var dates = [];
    for (var year = startDate.year(); year <= moment().year(); year++) {
        var endMonth = year != moment().year() ? 11 : moment().month();
        var startMonth = year === startDate.year() ? startDate.month() : 0;
        for (var currentMonth = startMonth; currentMonth <= endMonth; currentMonth = currentMonth > 12 ? currentMonth % 12 || 11 : currentMonth + 1) {
            var month = currentMonth + 1;
            var displayMonth = month < 10 ? '0' + month : month;
            dates.push([year, displayMonth, '01'].join('-'));
        }
    }
    return dates;
};

答案 8 :(得分:0)

这是我的解决方案,借助数学和O(n)

determineMonthInInterval(startDate, endDate) {

    let startYear = startDate.getFullYear();
    let endYear = endDate.getFullYear();

    let startMonth = startDate.getMonth() + 1;
    let endMonth = endDate.getMonth() + 1;

    let monthAmount = (endMonth - startMonth) + 1 + (12 * (endYear - startYear));

    let dates = [];
    let currMonth = startMonth;
    let currYear = startYear;
    for( let i=0; i<monthAmount; i++){
        
        let date = new Date(currYear + "/"+currMonth+"/1");
        dates.push(date);

        currYear = startYear + Math.floor((startMonth+i) / 12);
        currMonth = (currMonth) % 12 +1;

    }

    return dates;
}

答案 9 :(得分:0)

这是另一种选择:

getRangeOfMonths(startDate: Date, endDate: Date) {
    const dates = new Array<string>();
    const dateCounter = new Date(startDate);
    // avoids edge case where last month is skipped
    dateCounter.setDate(1);
    while (dateCounter < endDate) {
      dates.push(`${dateCounter.getFullYear()}-${dateCounter.getMonth() + 1}`);
      dateCounter.setMonth(dateCounter.getMonth() + 1);
    }
    return dates;
  }