How to get yesterday's date using JavaScript

By

Learn how to get yesterday's date in JavaScript by taking today's Date and calling setDate() with getDate() minus 1, which even handles month boundaries.

~~~

Well, first you get the date at the current time (today), then you subtract a day from it:

const today = new Date()
const yesterday = new Date(today)

yesterday.setDate(yesterday.getDate() - 1)

today.toDateString()
yesterday.toDateString()

We use the setDate() method on yesterday, passing as parameter the current day minus one.

getDate() returns the day of the month, a number from 1 to 31. setDate() sets it. So if today is the 10th, we’re setting the day to 9, same month, same year.

What happens at the start of a month?

Even if it’s day 1 of the month, JavaScript is logical enough and it will point to the last day of the previous month.

If today is March 1, getDate() returns 1, and we ask setDate() to set the day to 0. There’s no day 0, so the date rolls back to the last day of February:

const today = new Date(2025, 2, 1) //March 1, 2025
const yesterday = new Date(today)
yesterday.setDate(yesterday.getDate() - 1)

yesterday.toDateString() //'Fri Feb 28 2025'

The same rollover handles year boundaries. Yesterday relative to January 1, 2025 is December 31, 2024. Leap years work too: the day before March 1, 2024 is February 29.

Why the copy?

Notice we don’t call setDate() on today directly. Date objects are mutable: setDate() changes the object in place instead of returning a new one.

This is the pitfall to watch for:

const today = new Date()
today.setDate(today.getDate() - 1)
//today now holds yesterday's date

The variable is still named today, but it points to yesterday. Any code reading it later gets the wrong date. The fix is what we did at the top: create a copy with new Date(today), and mutate the copy.

What about the time?

Subtracting a day only changes the date part. The hours, minutes and seconds stay whatever they were when you created the object.

If you want yesterday at midnight, say to compare dates without caring about the time, zero it out:

const yesterday = new Date()
yesterday.setDate(yesterday.getDate() - 1)
yesterday.setHours(0, 0, 0, 0)

One last note: all of this works in local time. If you print the date with toISOString(), you get UTC, and near midnight that can show a different day than toDateString() does. For a “what day was yesterday” answer, stick with the local methods.

~~~

Related posts about js: