JavaScript: get all months between two dates?

I have two date strings like this:

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

And I want to end up with an array of strings like this:

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

So far this is what I've got, but it's pretty ugly:

var startDate = '2012-04-01';
var endDate = '2014-11-01';
var start = new Date(Date.parse(startDate));
var end = new Date(Date.parse(endDate))
var dates = [];
for (var i = start.getFullYear(); i < end.getFullYear() + 1; i++) {
    dates.push(i + '-' + '-01');
}
console.log(dates);

Is there a better way? JSFiddle.


Solution 1:

This should produce the desired output:

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

Just call it with your existing date format:

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"]

Solution 2:

You can also use the excellent moment.js library:

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

Solution 3:

If loading an extra library isn't a problem, you could always try the awesome MomentJS.
Gives for very clean and powerful date manipulation.

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

Solution 4:

  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/

Solution 5:

You are handling "logical" jumps, so you doesn't actually need timing arthmetics. So this is a simple counting problem:

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);