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!
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!
Share Improve this question asked Feb 25, 2015 at 13:55 IreneIrene 5812 gold badges10 silver badges20 bronze badges 04 Answers
Reset to default 3Try 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);
}
- Step forward one month
- Set the date to first of the month
- Step back one day (last day of previous month)
- Write the date (prepend 0 and use slice() to get the last two characters)
- Step forward one day to return to next month
- Increment the month
You got sybmol like that "011" because of "0" + 11 in js
it equals 011. So you should convert like this +(d.getMonth())
to number before sum.
This code should be correct:
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()
console.log(newdate);
}
Like this:
var d = new Date();
for (var i = 0, size = 24; i < size; i++){
d.setMonth(d.getMonth() + 1);
console.log(d.getDate() + "-" + (d.getMonth() + 1) + '-' + d.getFullYear())
}
After first 12 months, you need to increment year and reset month to 0. You keep trying to increment month beyond the 12 months.