Akshay Khetrapal Akshay Khetrapal - 4 months ago 19
Node.js Question

Dealing with dynamic date differences

  1. I have a form where I am accepting a duration. This could be a month, a year, 2 months, 20 days etc.

  2. Based on this duration, an email is shot to all the kids who have their birthdays x days before this duration.

  3. 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.

  4. 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?


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' +

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.