Check if a date is in the past in JavaScript
By Flavio Copes
Learn how to check if a JavaScript date falls on a past day compared to another, using setHours(0,0,0,0) to ignore the time and compare only the calendar day.
To check if a date falls on a past day compared to another, reset both dates to midnight with setHours(0, 0, 0, 0) and compare the resulting timestamps. This way the time of day doesn’t affect the comparison.
I had this problem: I wanted to check if a date referred to a past day, compared to another date.
Just comparing them using getTime() was not enough, as dates could have a different time. A date at 9 AM today is not “in the past” compared to today at 5 PM, at least not for my use case. I cared about calendar days, not instants.
I ended up using this function:
const firstDateIsPastDayComparedToSecond = (firstDate, secondDate) => {
if (firstDate.setHours(0,0,0,0) - secondDate.setHours(0,0,0,0) >= 0) { //first date is in future, or it is today
return false
}
return true
}
I use setHours() to make sure we compare 2 dates at the same time (00:00:00).
How does it work?
setHours(0, 0, 0, 0) sets the hours, minutes, seconds and milliseconds of the date to zero. It returns the updated timestamp, a number of milliseconds.
So the function compares two midnights. If the first midnight is earlier than the second, the first date is on a past day.
The comparison uses the local timezone, which is what you want when comparing calendar days as the user sees them.
Here is the same function with the implicit return, less bloated:
const firstDateIsPastDayComparedToSecond = (firstDate, secondDate) => firstDate.setHours(0,0,0,0) - secondDate.setHours(0,0,0,0) < 0
And here is how to use it with a simple example, comparing yesterday to today:
const today = new Date()
const yesterday = new Date(today)
yesterday.setDate(yesterday.getDate() - 1)
firstDateIsPastDayComparedToSecond( yesterday, today) //true
firstDateIsPastDayComparedToSecond( today, yesterday) //false
Watch out: setHours() mutates the dates
There’s a catch. setHours() doesn’t just return a timestamp. It also modifies the Date object in place.
After calling the function, both dates you passed in are reset to midnight:
const deadline = new Date('2026-08-07T15:30:00')
firstDateIsPastDayComparedToSecond(deadline, new Date())
deadline.getHours() //0, the 15:30 time is gone
If you need those dates later with their original time, that’s a bug waiting to happen.
The fix is to copy the dates inside the function, and let setHours() mutate the copies:
const firstDateIsPastDayComparedToSecond = (firstDate, secondDate) =>
new Date(firstDate).setHours(0, 0, 0, 0) < new Date(secondDate).setHours(0, 0, 0, 0)
Passing a date to new Date() creates a clone. The originals stay untouched, and the comparison works the same.
Related posts about js: