An often ignored feature of the Javacript Date object is that setting the individual date attributes (date, month, year, etc) to values beyond their normal range will automatically
adjust the other date attributes so that the resulting date is valid.
For example, if d
is a date then you can do d.setDate (d.getDate () + 20)
and d
will be the date 20 days later having adjusted months and even years appropriatley as necessary.
Using this, the following function takes a start date and a duration object and returns the date after the specified time period :
function dateAfter (date, duration) {
if (typeof duration === 'number') // numeric parameter is number of days
duration = {date:duration};
duration.year && date.setYear (date.getYear () + duration.year);
duration.month && date.setMonth (date.getMonth () + duration.month);
duration.date && date.setDate (date.getDate () + duration.date);
return date;
}
// call as follows :
var date = dateAfter (new Date (2012, 5, 15), {year: 1}); // adds one year
console.log (date);
date = dateAfter (date, {month:5, date: 4}); // adds 5 months and 4 days
console.log (date);
date = dateAfter (date, 7 * 4); // adds 4 weeks
console.log (date);
// to return the end date asked by the op, use
var date = dateAfter (new Date (2012, 5, 15), {year: 1, date: -1});