Camkode
Camkode

Get Monday and Sunday of the Week in JavaScript

Posted by Kosal

Get Monday and Sunday of the Week in JavaScript

To get the Monday and Sunday of the week, use the setDate() method to set the day of the month of a date to the Monday and Sunday of the week and pass the result to the Date() constructor.

const today = new Date()
const day = today.getDay()
const diff = today.getDate() - day + (day === 0 ? -6 : 1)
const monday = new Date(today.setDate(diff))

const sunday = new Date(monday)
sunday.setDate(sunday.getDate() + 6)

console.log(monday) // Monday November 21 2022
console.log(sunday) // Sunday November 27 2022

The getDate() method returns the day of the month (1 to 31) of a date.

The getDay() method returns the day of the week for the specified date according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.

function getMonday(d) {
  date = new Date(d)
  const day = date.getDay()
  const diff = date.getDate() - day + (day === 0 ? -6 : 1)
  return new Date(d.setDate(diff))
}

function getThisWeek() {
  const monday = getMonday(new Date())
  const sunday = new Date(monday)
  sunday.setDate(sunday.getDate() + 6)
  return { monday, sunday }
}

const { monday, sunday } = getThisWeek()
console.log(monday) // Monday November 21 2022
console.log(sunday) // Sunday November 27 2022