Get the first Day of the current Week in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 24 20212 min read

banner

Photo by Jonatan Pie

Get the first Day of the current Week #

To get the first day of the current week, get the day of the month, subtract the day of the week and add 1 to consider Monday the first day of the week.

index.js
function getFirstDayOfWeek(d) { // ๐Ÿ‘‡๏ธ clone date object, so we don't mutate it const date = new Date(d); const day = date.getDay(); // ๐Ÿ‘‰๏ธ get day of week // ๐Ÿ‘‡๏ธ day of month - day of week (-6 if Sunday), otherwise +1 const diff = date.getDate() - day + (day === 0 ? -6 : 1); return new Date(date.setDate(diff)); } // ๐Ÿ‘‡๏ธ Mon Oct 18 2021 19:06:39 GMT console.log(getFirstDayOfWeek(new Date()));

First, we create a new date object, so we don't mutate the passed in date.

We used the getDay method to get the day of the week.

This method returns an integer from 0 (Sunday) to 6 (Saturday).

Then we used the getDate method to get the day of the month.

To get the first day of the week, we subtract the day of the week from the day of the month. If the day of the week is Sunday, we subtract -6 to get Monday, if it is any other day we add 1, because the getDay method returns a zero-based value.

We used the setDate method to change the day of the month of the Date object.

This is why we created the copy on the first line of the function.

If you consider Sunday the first day of the week, use this function instead.

index.js
function getFirstDayOfWeek(d) { const date = new Date(d); const day = date.getDay(); const diff = date.getDate() - day; return new Date(date.setDate(diff)); } // ๐Ÿ‘‡๏ธ Sun Oct 24 2021 19:18:50 GMT console.log(getFirstDayOfWeek(new Date()));

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee