Borislav Hadzhiev
Sun Jan 16 2022·2 min read
Photo by Savvas Kalimeris
To get the date of the previous Sunday, use the setDate()
method, setting
the date to the result of subtracting the day of the week from the day of the
month. The setDate
method changes the day of the month of the specific Date
instance.
function getPreviousSunday(date = new Date()) { const previousMonday = new Date(); previousMonday.setDate(date.getDate() - date.getDay()); return previousMonday; } // 👇️ "Sun Jan 09 2022 16:25:00" console.log(getPreviousSunday(new Date('2022-01-12'))); // 👇️ "Sun Jan 23 2022 16:25:00" console.log(getPreviousSunday(new Date('2022-01-24')));
We created a reusable function that takes a Date
object as a parameter and
returns the previous Sunday.
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 the previous Sunday, we subtracted the day of the week from the day of the month.
The getDate() method returns an integer between 1 and 31, representing the day of the month.
The getDay() method returns an integer between 0 and 6, representing the day of the week, where Sunday is 0, Monday is 1, Tuesday is 2, etc.
For example the 2022-01-12
is a Wednesday, so the getDay
method would return
3
as the day of the week, 12 - 3 = 9
, which is the day of the month of the
previous Sunday.
If we pass a Date object that has is already a Sunday to the function, e.g.
2022-01-09
, we would get 9 - 0 = 9
, so the function would return a date that
stores the same Sunday.
function getPreviousSunday(date = new Date()) { const previousMonday = new Date(); previousMonday.setDate(date.getDate() - date.getDay()); return previousMonday; } // 👇️ "Sun Jan 09 2022 16:25:00" console.log(getPreviousSunday(new Date('2022-01-09')));
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.
function getPreviousSunday(date = new Date()) { const previousMonday = new Date(); previousMonday.setDate(date.getDate() - date.getDay()); previousMonday.setHours(0, 0, 0, 0); return previousMonday; } // 👇️ "Sun Jan 09 2022 00:00:00" console.log(getPreviousSunday(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.