Get First and Last Day of the current Week in JavaScript

avatar

Borislav Hadzhiev

Thu Apr 14 20222 min read

Updated - Thu Apr 14 2022

Get First and Last Day of the current Week in JavaScript #

To get the first and last days of the current week, use the setDate() method to change the day of the month of a date to the first and last days of the current week and pass the result to the Date() constructor.

index.js
const today = new Date(); const firstDay = new Date(today.setDate(today.getDate() - today.getDay())); const lastDay = new Date(today.setDate(today.getDate() - today.getDay() + 6)); console.log(firstDay); // 👉️ Sunday April 10 2022 console.log(lastDay); // 👉️ Saturday April 16 2022

The code snippet above considers Sunday to be the first day of the week and Saturday to be the last.

If your use case needs Monday to be the first day and Sunday to be the last, use this code snippet instead.

index.js
const today = new Date(); const firstDay = new Date(today.setDate(today.getDate() - today.getDay() + 1)); const lastDay = new Date(today.setDate(today.getDate() - today.getDay() + 7)); console.log(firstDay); // 👉️ Monday April 11 2022 console.log(lastDay); // 👉️ Sunday April 17 2022

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 and 6 that represents the day of the week for the given date: 0 is Sunday, 1 is Monday, 2 is Tuesday, etc.

The day of the month for the first day of the week is equal to day of the month - day of the week. If you consider Monday to be the first day of the week, add 1 to the result.

The day of the month for the last day of the week is equal to first day of the week + 6.

The last step is to use the setDate method, which takes the day of the month as a parameter and changes the value on the specific date.

The setDate() method returns the number of milliseconds between January 1st, 1970 and the given date.

To get a new Date object that represents the first day of the week, we pass the timestamp to the Date() constructor.

We repeated the same process to create a Date object that stores the last day of the week.

Use the search field on my Home Page to filter through my more than 1,000 articles.