Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function to add X months to a date

I’m looking for the easiest, cleanest way to add X months to a JavaScript date.

I’d rather not handle the rolling over of the year or have to write my own function.

Is there something built in that can do this?

like image 646
Chad Avatar asked Oct 21 '22 04:10

Chad


People also ask

What does the JavaScript Date () function do?

Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date objects, using either local time or UTC (universal, or GMT) time.


1 Answers

The following function adds months to a date in JavaScript (source). It takes into account year roll-overs and varying month lengths:

function addMonths(date, months) {
    var d = date.getDate();
    date.setMonth(date.getMonth() + +months);
    if (date.getDate() != d) {
      date.setDate(0);
    }
    return date;
}

// Add 12 months to 29 Feb 2016 -> 28 Feb 2017
console.log(addMonths(new Date(2016,1,29),12).toString());

// Subtract 1 month from 1 Jan 2017 -> 1 Dec 2016
console.log(addMonths(new Date(2017,0,1),-1).toString());

// Subtract 2 months from 31 Jan 2017 -> 30 Nov 2016
console.log(addMonths(new Date(2017,0,31),-2).toString());

// Add 2 months to 31 Dec 2016 -> 28 Feb 2017
console.log(addMonths(new Date(2016,11,31),2).toString());

The above solution covers the edge case of moving from a month with a greater number of days than the destination month. eg.

  • Add twelve months to February 29th 2020 (should be February 28th 2021)
  • Add one month to August 31st 2020 (should be September 30th 2020)

If the day of the month changes when applying setMonth, then we know we have overflowed into the following month due to a difference in month length. In this case, we use setDate(0) to move back to the last day of the previous month.

Note: this version of this answer replaces an earlier version (below) that did not gracefully handle different month lengths.

var x = 12; //or whatever offset
var CurrentDate = new Date();
console.log("Current date:", CurrentDate);
CurrentDate.setMonth(CurrentDate.getMonth() + x);
console.log("Date after " + x + " months:", CurrentDate);
like image 356
Chad Avatar answered Oct 24 '22 04:10

Chad