Sometimes, we want to get the first day of the week from the current date with JavaScript.
In this article, we’ll look at how to get the first date of the week from the current date with JavaScript.
Using Native Date Methods
We can use various date methods to get the first day of the week from the current date.
To do this, we can write:
const getMonday = (d) => {
const dt = new Date(d);
const day = dt.getDay()
const diff = dt.getDate() - day + (day === 0 ? -6 : 1);
return new Date(dt.setDate(diff));
}
console.log(getMonday(new Date(2021, 1, 20)));
We create the getMonday
function takes the d
date parameter.
In the function, create a Date
instance with the Date
constructor.
Then we call getDay
to get the day of the week.
It returns 0 for Sunday, 1 for Monday, and so on up to 6 for Saturday.
Then we get the difference between the current date of the week and the Monday of the same week by subtracting the day
and then add -6
back if day
is 0 and 1 otherwise.
And then we use the Date
constructor again by call setDate
on dt
with diff
to set the day to the Monday of the same week.
Therefore, the console log should log:
Mon Feb 15 2021 00:00:00 GMT-0800 (Pacific Standard Time)
as a result.
Conclusion
We can get the Monday of the same week of the given date by getting the day of the week.
Then we subtract the date by the day of the week then add back the number of days to reach the Monday of the same week of the date.