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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3