Get the Monday of the Current week using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 17, 2022

banner

Photo from Unsplash

Get the Monday of the Current week using JavaScript #

To get the Monday of the current week:

  1. Calculate the day of the month of the Monday of the current week.
  2. Use the setDate() method to get the timestamp of the Monday of the current week.
  3. Pass the result to the Date() constructor.
index.js
function getMondayOfCurrentWeek() { const today = new Date(); const first = today.getDate() - today.getDay() + 1; const monday = new Date(today.setDate(first)); return monday; } // 👇️ Mon Jan 17 2022 console.log(getMondayOfCurrentWeek());

The getDate method returns an integer between 1 and 31 that represents the day of the month for the given date.

The getDay method returns an integer between 0 (Sunday) and 6 (Saturday) that represents the day of the week for the date.

We subtracted the day of the week from the day of the month and added 1 to the result to get the day of the month for the Monday of the current week.

We had to add 1 because the getDay method is zero-indexed and considers Sunday to be the first day of the week.

The setDate method takes the day of the month as a parameter, changes the value of the Date on which it was called and returns the number of milliseconds between the 1st of January 1970 and the given date.

We directly passed the timestamp to the Date() constructor to store the date of the current Monday.

You can use this approach to get any of the days of the current week.

Here is an example that logs the value of the Tuesday of the current week.

index.js
function getMondayOfCurrentWeek() { const today = new Date(); const first = today.getDate() - today.getDay() + 1; const tuesday = new Date(today.setDate(first + 1)); console.log(tuesday); // 👉️ Tue Jan 18 2022 const monday = new Date(today.setDate(first)); return monday; } // 👇️ Mon Jan 17 2022 console.log(getMondayOfCurrentWeek());

We used the same approach to get the date of the current Tuesday.

We simply had to add 1 to the day of the month of the current Monday and pass the result to the setDate() method.

To get the date of the current Wednesday, you would add 2 to day of the month of the current Monday, etc.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.