Sometimes, we want to get first and last day of the current week in JavaScript.
In this article, we’ll look at how to get first and last day of the current week in JavaScript.
How to get first and last day of the current week in JavaScript?
To get first and last day of the current week in JavaScript, we can use some date methods.
For instance, we write
const curr = new Date();
const first = curr.getDate() - curr.getDay();
const last = first + 6;
const firstDay = new Date(curr.setDate(first)).toUTCString();
const lastDay = new Date(curr.setDate(last)).toUTCString();
to create the curr
date with the current datetime.
And then we get the difference between the first day of the week and the current day of the month with
curr.getDate() - curr.getDay()
And then we get the last day of the week with first + 6
.
Next, we use setDate
with first
and last
to get the first and last day of the week.
And then we create a new Date
object from the dates.
We use toUTCString
to return human readable date strings for each date.
Conclusion
To get first and last day of the current week in JavaScript, we can use some date methods.