How can I get the dates for the current week in JavaScript?

Viewed 29

I'd like to be able to get the first and the last date of the current week. For example, this week would be September 4th to September 10th.

The issue I'm running into happens at the end of the month when there are dates from two months (like the last month of August). This caused a problem because the date range was displayed as August 28th to August 3rd when it should've been September 3rd.

I saw some other posts recommending Moment.js, but the Docs say that it shouldn't be used in new projects. What's a good way to do this?

1 Answers
  1. Get the current date: const start = new Date();
  2. Shift that back by the current day-of-week: start.setDate(start.getDate() - start.getDay());
  3. Make a new date based on that: const end = new Date(start);
  4. Shift that date forward: end.setDate(end.getDate() + 6);

That will give you a Sunday to Saturday week. You can shift the days as necessary based on what you consider a "week" to be.

The JavaScript Date API will deal with month shifts automatically. Thus if it's Thursday September 1, moving the day-of-month back to Sunday will correctly give the date in August.

Related