Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all month between 2 dates with moment.js?

I've two dates

2015-3-30      2013-8-31

How can I make a month list like:

[ '2015-3', '2015-2', '2015-1', '2014-12', '2014-11', '2014-10', '2014-09', '2014-08', '2014-07', '2014-06', '2014-05'....., '2013-08' ] 

Thanks.

like image 990
Tachun Lin Avatar asked Apr 06 '15 07:04

Tachun Lin


2 Answers

This should do it:

var dateStart = moment('2013-8-31');
var dateEnd = moment('2015-3-30');
var timeValues = [];

while (dateEnd > dateStart || dateStart.format('M') === dateEnd.format('M')) {
   timeValues.push(dateStart.format('YYYY-MM'));
   dateStart.add(1,'month');
}
like image 200
vinjenzo Avatar answered Nov 18 '22 13:11

vinjenzo


I think the original answer isn't entirely correct, as you wouldn't get '2015-3' in your array. This is due to the fact your start date would eventually end up as '2015-3-31' and would fail the conditional in place. You could extend it like below.

UPDATE: I've now included cloning the dateStart variable so it isn't mutated at all.

var dateStart = moment('2013-8-31');
var dateEnd = moment('2015-3-30');
var interim = dateStart.clone();
var timeValues = [];

while (dateEnd > interim || interim.format('M') === dateEnd.format('M')) {
   timeValues.push(interim.format('YYYY-MM'));
   interim.add(1,'month');
}
like image 33
Alexander Swann Avatar answered Nov 18 '22 13:11

Alexander Swann