Reputation: 2676
I have a form where I am accepting a duration. This could be a month, a year, 2 months, 20 days etc.
Based on this duration, an email is shot to all the kids who have their birthdays x days before this duration.
Since, a person can be born in a month with either 28, 29, 30 or 31 days, this makes calculating the date difference a pain.
What I've done so far is converted months -> 30 days, years -> 365 days and based on this done my calculations.
What is a more elegant way to deal with such dynamic date differences taking into account different months and leap years?
Upvotes: 0
Views: 86
Reputation: 2089
You can just use vanilla js for that -
for months -
var d = new Date();
d.setMonth(d.getMonth() - x);
for years -
var d = new Date();
d.setYear(d.getYear() - x);
for days -
var d = new Date();
d.setDate(d.getDate() - x);
Upvotes: 1
Reputation: 147403
Adding days, months and years is fairly straight forward. When adding months, just check that the date in the new month is the same as the initial month and if it isn't, set the date to 0 (i.e. you've rolled over an extra month so set the date to the end of the previous month). Same for adding years, but it will only happen for February. E.g.
function addMonths(date, months) {
var d = new Date(+date);
var startDate = d.getDate();
d.setMonth(d.getMonth() + months);
if (d.getDate() != startDate) d.setDate(0);
return d;
}
function addYears(date, years) {
return addMonths(date, years * 12);
}
var d = new Date(2016,4,31);
console.log(d.toLocaleString() + ' plus one month is \n' +
addMonths(d,1).toLocaleString());
d = new Date(2016,1,29);
console.log(d.toLocaleString() + ' plus one year is \n' +
addYears(d, 1).toLocaleString());
You can even add these as methods to Date.prototype for convenience.
Note that date arithmetic isn't necessarily symmetric.
Upvotes: 1