Get a date object (six months prior) from another date object

Viewed 31790

How can I create a date object which is less than n number of months from another date object? I am looking for something like DateAdd().

Example:

var objCurrentDate = new Date();

Now using objCurrentDate, how can I create a Date object having a date which is six months older than today's date / objCurrentDate?

4 Answers

You have to be careful because dates have a lot of edge cases. For example, merely changing the month back by 6 doesn't account for the differing number of days in each month. For example, if you run a function like:

function addMonths(date, months) {
date.setMonth((date.getMonth() + months) % 12);
return date;
}

addMonths(new Date(2020, 7, 31), -6); //months are 0 based so 7 = August

The resulting date to return would be February 31st, 2020. You need to account for differences in the number of days in a month. Other answers have suggested this in various ways, by moving it to the first of the month, or the last of the month, or the first of the next month, etc. Another way to handle it is to keep the date if it is valid, or to move it to the end of the month if it overflows the month's regular dates. You could write this like:

function addMonths(date, months) {
  var month = (date.getMonth() + months) % 12;
  //create a new Date object that gets the last day of the desired month
  var last = new Date(date.getFullYear(), month + 1, 0);

  //compare dates and set appropriately
  if (date.getDate() <= last.getDate()) {
    date.setMonth(month);
  }

  else {
    date.setMonth(month, last.getDate());
  }

  return date;
}

This at least ensures that the selected day won't "overflow" the month that it is being moved to. Finding the last day of the month with the datePart = 0 method is documented here.

This function still leaves a lot to be desired, as it doesn't add years and you can't subtract more than a year (or you will run into a new issue with negatives being involved). However, fixing those and the other issues you may run into (namely timezones) will be left as an exercise for the reader.

Related