Borislav Hadzhiev
Thu Jan 27 2022·2 min read
Photo by Kinga Cichewicz
To increment a date by 1 month:
getMonth()
method to get the value for the month of the given date.setMonth()
method to increment the month by 1
.const date = new Date(); date.setMonth(date.getMonth() + 1); // ✅ Increment Date by 1 month console.log(date); // 👉️ Sun Feb 27 2022 (today is 27 Jan) // ✅ Set date to 1st day of next month const date2 = new Date(); const firstDayNextMonth = new Date(date2.getFullYear(), date.getMonth(), 1); console.log(firstDayNextMonth); // 👉️ Tue Feb 01 2022 (today is 27 Jan)
The first example shows how to increment the date by 1
month.
The
getMonth()
method returns an integer between 0
(January) and 11
(December),
representing the month in the given date.
Notice that the value is zero-based, e.g. January = 0, February = 1, March = 2, etc.
The setMonth() method takes a zero-based value representing the month of the year (0 = January, 1 = February, etc.) and sets the value for the date.
The JavaScript Date
object automatically takes care of rolling over the year
if incrementing the month pushes us into the next year.
const date = new Date('2022-12-21'); date.setMonth(date.getMonth() + 1); // ✅ Increment Date by 1 month console.log(date); // 👉️ Sat Jan 21 2023
We created a Date
object with a value of the 21st of December and incremented
the date by 1
month, which pushed us into January 2023.
setMonth
method mutates the Date
object it was called on. If you don't want to change the Date
in place, you can create a copy of it before calling the method.const date = new Date('2022-03-29'); const dateCopy = new Date(date.getTime()); dateCopy.setMonth(dateCopy.getMonth() + 1); console.log(dateCopy); // 👉️ Fri Apr 29 2022 console.log(date); // 👉️ Tue Mar 29 2022 (didn't change original)
The getTime method returns the number of milliseconds elapsed between 1st of January, 1970 00:00:00 and the given date.
Date
object, so we don't mutate it in place when calling the setMonth
method.Copying the date is quite useful when you have to use the original Date
object
in other places in your code.
Date()
constructor instead.// ✅ Set date to 1st day of next month const date2 = new Date(); const firstDayNextMonth = new Date(date2.getFullYear(), date.getMonth(), 1); console.log(firstDayNextMonth); // 👉️ Tue Feb 01 2022 (today is 27 Jan)
The 3 parameters we passed to the Date()
constructor are - the year, month and
day of the month.
We incremented the month by 1
and set the day of the month value to 1
.
If you need to set the day of the month value to a different day, simply change the third parameter.
You can also use the getDate()
method to get the day of the month for the
given date.
const date = new Date('2022-03-29'); // 👇️ 29 console.log(date.getDate());