1

So for example, monday is sep 28, a week from monday, sunday is oct 4. How Can I get the first and last day of the week? So far the solutions cover only days belonging in the same month. Please help. Thanks

JZnrgn
  • 41
  • 5

3 Answers3

1

You can add a week to the starting date's time and construct a new date:

const DAY = 1000 * 60 * 60 * 24; // ms * seconds * minutes * hours
const WEEK = DAY * 7;

const today = new Date('2020-09-29');
const nextWeek = new Date(today.getTime() + WEEK);

console.log(nextWeek.toUTCString());

Then add or subtract from that date to get the first/last day of the week if necessary.

const DAY = 1000 * 60 * 60 * 24;
const WEEK = DAY * 7;

const today = new Date('2020-09-29');
const nextWeek = new Date(today.getTime() + WEEK);

const day = nextWeek.getDay(); // 0 sunday, 6 saturday

const firstDay = new Date(nextWeek.getTime() - (day * DAY));
const lastDay = new Date(nextWeek.getTime() + ((6 - day) * DAY));

console.log(firstDay.toUTCString()); // monday
console.log(lastDay.toUTCString()); // sunday
ray
  • 26,557
  • 5
  • 28
  • 27
1

You can use date-fns library for that:

const start = startOfWeek(date);
const end = endOfWeek(date);

Check out these threads for more solutions:

maximus
  • 716
  • 7
  • 18
1

You want to look into the Date.getDay() method. This returns a number from 0-6 for the day of the week (Sunday is 0).

As a function, it could look like this:

function getMonday(date){
  const originalDay = date.getDay();
  const monday = 1;
  const newDate = new Date(date);
  const delta = originalDay === 0 ? 1 : originalDay - monday;
  newDate.setDate(newDate.getDate() - delta);
  return newDate;
}
Dave Cook
  • 617
  • 1
  • 5
  • 17
  • Thanks for taking interest in my post. I have resolved the issue now. Thank you very much!:D – JZnrgn Sep 30 '20 at 19:23