Categories
JavaScript Answers

How to Get the Date of Next Monday with JavaScript?

Spread the love

Sometimes, we want to get the date of next Monday with JavaScript.

In this article, we’ll look at how to get the date of next Monday with JavaScript.

Get the Date of Next Monday with JavaScript

To get the date of next Monday with JavaScript, we can use the setDate, getDate and getDay methods.

To use them, we write:

const d = new Date();
d.setDate(d.getDate() + ((7 - d.getDay()) % 7 + 1) % 7);
console.log(d);

We create a date object with today’s date and time with the Date constructor and assign it to d.

Then we call setDate with the date for next Monday.

To get the date for next Monday, we first get the day of the month for today’s date with getDate.

Then we add the number of days until the date reaches Monday.

To get the difference between next Monday and today, we call getDay to get the day of the week.

Then we multiply that by -1 and add 7 to the returned result, which is:

7 - d.getDay()

Then we get the remainder of that divided by 7, which is:

(7 - d.getDay()) % 7

And then we add 1 to the whole expression.

This will get the day of the month for next Monday or the Monday after, so we have to get the remainder of that divided by 7 again.

And we add that to the date of d.

After we call setDate with the whole expression, we get the date and time for next Monday.

Conclusion

To get the date of next Monday with JavaScript, we can use the setDate, getDate and getDay methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *