Home > Web Front-end > JS Tutorial > How to Reliably Add Months to a JavaScript Date?

How to Reliably Add Months to a JavaScript Date?

Susan Sarandon
Release: 2024-12-04 13:21:14
Original
519 people have browsed it

How to Reliably Add Months to a JavaScript Date?

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:

  • Takes a JavaScript Date object as input (date).
  • Adds a specified number of months (months) to the date.
  • Handles year roll-overs and adjusts for varying month lengths automatically.
  • Returns a new Date object with the modified date.

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());
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template