Borislav Hadzhiev
Fri Jan 14 2022·2 min read
Photo by Jeremy Bishop
Use the setDate()
method to get the previous day of a date, e.g.
date.setDate(date.getDate() - 1)
. The setDate
method takes the day of the
month as a parameter and changes the value for the Date
instance.
function getPreviousDay(date = new Date()) { const previous = new Date(date.getTime()); previous.setDate(date.getDate() - 1); return previous; } console.log(getPreviousDay()); // 👉️ yesterday // 👇️ Fri Dec 23 2022 console.log(getPreviousDay(new Date('2022-12-24'))); // 👇️ Sat Dec 31 2022 console.log(getPreviousDay(new Date('2023-01-01')));
We created a reusable function that returns the previous day of a date.
We defined the previous
variable because the
setDate
method mutates the Date
object it was called on.
This might not be what you want if you need to preserve the passed in date object.
Date
object that stores the same date and time.The setDate
method takes an integer 1-31
that represents the day of the
month and changes the value on the given Date
object.
We used the getDate method to get the day of the month for the specific date and decremented the result by 1.
The getDate
method returns an integer between 1
and 31
.
getPreviousDay
function, so if the user does not pass in a Date object, the method returns yesterday's date.Note that the Date object automatically handles the scenario that the date is the first of the month.
If that is the case, the Date
object rolls back to the previous month
automatically.
function getPreviousDay(date = new Date()) { const previous = new Date(date.getTime()); previous.setDate(date.getDate() - 1); return previous; } // 👇️ Tue Jan 31 2023 console.log(getPreviousDay(new Date('2023-02-01'))); // 👇️ Sat Dec 31 2022 console.log(getPreviousDay(new Date('2023-01-01')));
As you can see the Date
object also handles the scenario where the previous
day is the last day of the previous year.