Get the Friday of the Current Week using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 17, 2022

banner

Photo from Unsplash

Get the Friday of the Current Week using JavaScript #

To get the Friday of the current week:

  1. Calculate the day of the month of the Monday of the current week.
  2. Add 4 to the result.
  3. Use the setDate() method to get the timestamp of the Friday of the current week.
  4. Pass the result to the Date() constructor.
index.js
function getFridayOfCurrentWeek() { const today = new Date(); const first = today.getDate() - today.getDay() + 1; const fifth = first + 4; const friday = new Date(today.setDate(fifth)); return friday; } // 👇️ Fri Jan 21 2022 console.log(getFridayOfCurrentWeek());

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 Friday of the current week by adding 4 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 Friday.

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

index.js
function getFridayOfCurrentWeek() { const today = new Date(); const first = today.getDate() - today.getDay() + 1; const fifth = first + 4; const saturday = new Date(today.setDate(fifth + 1)); console.log(saturday); // 👉️ Sat Jan 22 2022 const friday = new Date(today.setDate(fifth)); return friday; } // 👇️ Fri Jan 21 2022 console.log(getFridayOfCurrentWeek());

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

We simply added 1 to the day of the month of the current Friday and passed the result to the setDate() method.

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.