Get the Date of the Previous Monday using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 16, 2022

banner

Photo from Unsplash

Get the Date of the Previous Monday using JavaScript #

To get the date of the previous Monday:

  1. Add 6 to the day of the week and get the remainder of dividing by 7.
  2. Subtract the result from the day of the month.
index.js
function getPreviousMonday(date = new Date()) { const previousMonday = new Date(); previousMonday.setDate(date.getDate() - ((date.getDay() + 6) % 7)); return previousMonday; } // 👇️ "Mon Jan 10 2022 15:45:00" console.log(getPreviousMonday(new Date('2022-01-11'))); // 👇️ "Mon Jan 03 2022 15:45:00" console.log(getPreviousMonday(new Date('2022-01-09')));

We created a reusable function that takes a Date object as a parameter and returns the previous Monday.

If no parameter is provided, the function returns the previous Monday of the current date.

The setDate method allows us to change the day of the month of a specific Date instance.

The method takes an integer that represents the day of the month.

To get to the previous Monday, we:

  1. Add 6 to the day of the week, e.g. Tuesday = 2 + 6 = 8. Note that the getDay() method returns the day of the week where Sunday is 0, Monday is 1, Tuesday is 2, etc.
  2. Use the modulo operator to get the remainder of dividing 8 % 7 = 1.
  3. The getDate() method returns the day of the month, e.g. 11 - 1 = 10.
  4. And 10 is the day of the month of the previous Monday.
Note that the setDate method mutates the Date object in place, changing it's day of the month value.

We created a new Date() object and stored it in the previousMonday variable to avoid mutating the passed in Date.

Note that if the function is passed a Date that is already a Monday, it returns the date as is.

For example 2022-01-10 is a Monday.

  1. Add 6 to the day of the wee, e.g. Monday = 1 + 6 = 7.
  2. Get the remainder - 7 % 7 = 0.
  3. And subtract the result from the day of the month - 10 - 0 = 10.
  4. And the method returns a new date that stores the same Monday.

If you want to reset the time of the Date and set the hours, minutes, seconds and milliseconds to 0, you can use the setHours() method.

index.js
function getPreviousMonday(date = new Date()) { const previousMonday = new Date(); previousMonday.setDate(date.getDate() - ((date.getDay() + 6) % 7)); // 👇️ Reset hours, minutes, seconds, milliseconds to `0` previousMonday.setHours(0, 0, 0, 0); return previousMonday; } // 👇️ "Mon Jan 10 2022 00:00:00" console.log(getPreviousMonday(new Date('2022-01-12')));

The four parameters we passed to the setHours method are the hours, minutes, seconds and milliseconds.

This resets the time for the returned date to Midnight.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.