Add Months to Dates with JavaScript
If you need to increment or decrement a date by a specified number of months in JavaScript, there's a built-in solution that caters to your needs.
Function to Add Months to a Date
To simplify the process, you can utilize the following function that handles year roll-overs and month length variations:
function addMonths(date, months) { var d = date.getDate(); date.setMonth(date.getMonth() + +months); if (date.getDate() != d) { date.setDate(0); } return date; }
Example Usage
To add or subtract months from a date, simply call the function with the original date and the number of months to add or subtract.
// Add 12 months to 29 Feb 2016 var newDate = addMonths(new Date(2016,1,29),12); // Subtract 1 month from 1 Jan 2017 newDate = addMonths(new Date(2017,0,1),-1); // Add 2 months to 31 Dec 2016 newDate = addMonths(new Date(2016,11,31),2);
By leveraging this function, you can effortlessly manipulate dates in your JavaScript applications without having to worry about the details of month lengths or year roll-overs.
The above is the detailed content of How Can I Easily Add or Subtract Months to a Date in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!