Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: get all months between two dates?

Tags:

javascript

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.

like image 473
Richard Avatar asked May 26 '15 16:05

Richard


People also ask

How to find months between two dates in JavaScript?

To get the number of months between 2 dates: Use the getMonth() method to calculate the month difference between the two dates. Use the getFullYear() method to calculate the difference in years between the dates. Multiply the year difference by 12 and return the sum.


1 Answers

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"] 
like image 115
Rob M. Avatar answered Sep 21 '22 00:09

Rob M.