Get the Sunday of the Current Week using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 17, 2022

banner

Check out my new book

Get the Sunday of the Current Week using JavaScript #

To get the Sunday of the current week:

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

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.

Then, we got the day of the month for the Sunday of the current week by adding 6 to the result.

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 Sunday.

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 Monday of the current week.

index.js
function getSundayOfCurrentWeek() { const today = new Date(); const first = today.getDate() - today.getDay() + 1; const last = first + 6; const monday = new Date(today.setDate(first)); console.log(monday); // 👉️ Mon Jan 17 2022 const sunday = new Date(today.setDate(last)); return sunday; } // (today is Mon Jan 17 2022) // 👇️ Sun Jan 23 2022 console.log(getSundayOfCurrentWeek());

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

If you need to get the current Tuesday, you would add 2 instead of 1 when subtracting the day of the week from the day of the month.
Use the search field on my Home Page to filter through my more than 3,000 articles.