Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to generate monthly dates?

I need to calculate monthly dates, that is, given a particular date, generate dates for the next 2 years for example. I came up with the following code:

var d = new Date( '2007-12-31' );
  d.setMonth( d.getMonth() + 1 );
  for (var i = 1; i<24; i++){
    var newdate = d.getDate() + "-" + d.getMonth()+i + '-' + d.getFullYear()
    print(newdate);
  }

However, this is producing:

(...)
31-06-2008  (ok)
31-07-2008  (ok)
31-08-2008  (ok)
31-09-2008  (ok)
31-010-2008 (error, 3 characters for month) 
31-011-2008 (error, 3 characters for month)
31-012-2008 (error, 3 characters for month)
31-013-2008 (error, should be 31-01-2009)
31-014-2008 (error, should be 28-02-2009)

Please, is there any way of producing monthly dates considering some months are 30 or 31 days and February is 28 or 29 depending on the years? Thanks!

like image 558
Irene Avatar asked Feb 27 '26 04:02

Irene


1 Answers

Try the following:

var d = new Date(2007, 11, 31);
d.setDate(d.getDate()+1);
for(i=1; i<24; i++) { 
    d.setMonth(d.getMonth()+1);
    d.setDate(1);
    d.setDate(d.getDate()-1);
    document.write(d.getDate() + "-" + ("0" + (d.getMonth()+1)).slice(-2) + '-' + d.getFullYear() + '<br />');
    d.setDate(d.getDate()+1);
    }
  1. Step forward one month
  2. Set the date to first of the month
  3. Step back one day (last day of previous month)
  4. Write the date (prepend 0 and use slice() to get the last two characters)
  5. Step forward one day to return to next month
  6. Increment the month
like image 52
ElPedro Avatar answered Feb 28 '26 17:02

ElPedro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!