Skip to content

How to check if a date refers to a day in the past in JavaScript

FULL-STACK WEB DEVELOPMENT BOOTCAMP

2024 COHORT SIGNUPS END TOMORROW

Given a JavaScript date, how do you check if it references a day in the past?

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.

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).

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
  • Learn modern web development in my BOOTCAMP (SIGNUP END TOMORROW FEB 20, 2024)
  • THE VALLEY OF CODE (+ PRO), your web development manual
  • I wrote 15+ coding BOOKS, all available in THE VALLEY OF CODE PRO
  • Indie solopreneur internet business masterclass SOLO LAB (summer 2024)