Categories
JavaScript Answers

How to get the start date and end date of current week, with the week start from Monday and end with Sunday, with JavaScript?

Spread the love

Sometimes, we want to get the start date and end date of current week, with the week start from Monday and end with Sunday, with JavaScript.

In this article, we’ll look at how to get the start date and end date of current week, with the week start from Monday and end with Sunday, with JavaScript.

How to get the start date and end date of current week, with the week start from Monday and end with Sunday, with JavaScript?

To get the start date and end date of current week, with the week start from Monday and end with Sunday, with JavaScript, we can use some date methods.

For instance, we write:

const startAndEndOfWeek = (date) => {
  const now = date ? new Date(date) : new Date().setHours(0, 0, 0, 0);
  const monday = new Date(now);
  monday.setDate(monday.getDate() - monday.getDay() + 1);
  const sunday = new Date(now);
  sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
  return [monday, sunday];
}

const d = new Date(2022, 3, 1)
console.log(startAndEndOfWeek(d))

to define the startAndEndOfWeek function that takes a date.

In it, we compute the Monday and Sunday of the week that has the given date.

To do this, we create a copy of date with the Date constructor.

Then we get monday by creating a new date from now.

And then we call setDate with monday.getDate() - monday.getDay() + 1 to set the day of the week of monday to the Monday within the same week as date.

Likewise, we call setDate with sunday.getDate() - sunday.getDay() + 7 to set the day of the week of sunday to the Sunday within the same week as date.

Finally, we return both dates.

As a result, the console log logs  [Mon Mar 28 2022 00:00:00 GMT-0700 (Pacific Daylight Time), Sun Apr 03 2022 00:00:00 GMT-0700 (Pacific Daylight Time)].

Conclusion

To get the start date and end date of current week, with the week start from Monday and end with Sunday, with JavaScript, we can use some date methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *