0

I have let today = new Date() object. I need to get the Monday of the current week regardless if the week starts on Sunday or Monday. If the week starts on a Sunday and the today is Sunday I need to get the Monday on the previous week. Sunday should always be the last day. Any suggestions on how to solve this?

Now I use this, which at least works fine when the week starts on Monday.

// Get the monday date of current week
function getMondayOfCurrentWeek(d) {

  const date = new Date(d);
  const day = date.getDay(); // Sunday - Saturday : 0 - 6

  //  Day of month - day of week (-6 if Sunday), otherwise +1
  const diff = date.getDate() - day + (day === 0 ? -6 : 1);

  return new Date(date.setDate(diff));
}

console.log(
  getMondayOfCurrentWeek(new Date(2022,3,3)).toDateString()
);
RobG
  • 142,382
  • 31
  • 172
  • 209

1 Answers1

1

Your code DOES get the previous Monday on a Sunday

What does "If the week starts on a Sunday" mean to your?

In JS Sunday is the 0th or first day

// Get the monday date of current week
function getMondayOfCurrentWeek(d) {
  const date = new Date(d);
  const day = date.getDay(); // Sunday - Saturday : 0 - 6
  //  Day of month - day of week (-6 if Sunday), otherwise +1
  const diff = date.getDate() - day + (day === 0 ? -6 : 1);
  return date.setDate(diff), date;
}

console.log(getMondayOfCurrentWeek(new Date()).toDateString() )

console.log(getMondayOfCurrentWeek(new Date(2022,3,3,15,0,0,0)).toDateString() ); // Sunday 3rd of April 2022
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    When writing dates to the SO console it's nicer to use *toDateString* otherwise it shows as for *toISOString* which isn't that friendly. – RobG Apr 06 '22 at 14:15
  • Yep thanks for helping me sort this out. Now I see more clearly that it is not in this function my time zone-related issue lies. Thanks for the help! – Diana Nilsson Apr 06 '22 at 14:50
  • @DianaNilsson För al del :) – mplungjan Apr 07 '22 at 04:03