How to Add Months to a JavaScript Date
Adding months to a JavaScript date can be a tricky task if you want to handle year roll-overs and varying month lengths correctly. To simplify the process, consider utilizing a pre-built function.
The following JavaScript function provides a clean and straightforward solution (taken from this source):
Function: addMonths(date, months)
Description:
Example Usage:
// 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());
Output:
Sat Feb 28 00:00:00 GMT+0000 2017 Sun Dec 01 00:00:00 GMT+0000 2016 Wed Nov 30 00:00:00 GMT+0000 2016 Tue Feb 28 00:00:00 GMT+0000 2017
This function simplifies the task of adding months to a JavaScript date, providing reliable results without the need for complex date calculations.
The above is the detailed content of How to Reliably Add Months to a JavaScript Date?. For more information, please follow other related articles on the PHP Chinese website!