Home >Web Front-end >JS Tutorial >How Can I Easily Add Months to a Date in JavaScript?
Adding Months to a Date in JavaScript
JavaScript offers a built-in solution to effortlessly add months to a given date. The task of handling year roll-overs or varied month lengths can be left to the function, ensuring a seamless experience.
To leverage this feature, consider the following function:
function addMonths(date, months) { var d = date.getDate(); date.setMonth(date.getMonth() + +months); if (date.getDate() != d) { date.setDate(0); } return date; }
This function takes two arguments: the date and the number of months to add. It begins by storing the current day of the month in the variable d. Subsequently, it adds the desired number of months to the date. If this causes the day of the month to change, the date is adjusted to the last day of the new month.
To illustrate the function's functionality, consider the following examples:
The above is the detailed content of How Can I Easily Add Months to a Date in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!