Borislav Hadzhiev
Tue Jan 18 2022·2 min read
Photo by Sean Kong
To get the date of the next Monday:
setDate()
method.setDate
method changes the day of the month for the given date.function getNextMonday(date = new Date()) { const dateCopy = new Date(date.getTime()); const nextMonday = new Date( dateCopy.setDate( dateCopy.getDate() + ((7 - dateCopy.getDay() + 1) % 7 || 7), ), ); return nextMonday; } // 👇️ Get Monday of Next Week console.log(getNextMonday(new Date())); // 👉️ Mon Jan 24 2022 // 👇️ Get Next Monday for specific Date console.log(getNextMonday(new Date('2022-01-25'))); // 👉️ Mon Jan 31 2022
We created a reusable function that takes a Date
object as a parameter and
returns the next Monday.
If no parameter is provided, the function returns the next Monday of the current date.
The
setDate
method allows us to change the day of the month of a specific Date
instance.
The method takes an integer that represents the day of the month.
To get the next Monday, we:
Add 1
to the day of the week, e.g. Tuesday = 7 - 2 (Tuesday) + 1 = 6
.
Note that the
getDay()
method returns the day of the week where Sunday is 0, Monday is 1, Tuesday is
2, etc.
Use the modulo operator to get the remainder of dividing 6 % 7 = 6
If the remainder is equal to 0
, then the current date is Monday and we have
to default it to 7
to get the date of the next Monday.
The getDate()
method returns the day of the month, e.g. 18 + 6 = 24
,
where 24
is the day of the month for the next Monday.
If the Date
object stores a Monday:
17
.7 - day of the week (Monday = 1) + 1 = 7
7 % 7 = 0 || 7 = 7
.17 + 7 = 24
, where 24
is
the day of the month for the next Monday.We created the dateCopy
variable in the function because the setDate
method
mutates the Date
instance in place.
If you use the same Date
object elsewhere in your code, this might lead to
confusing bugs.