← flaviocopes.com

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

Updated Oct 24 2019

Psssst! The 2023 WEB DEVELOPMENT BOOTCAMP is starting on FEBRUARY 01, 2023! SIGNUPS ARE NOW OPEN to this 10-weeks cohort course. Learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much more! ✨

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

I write books for developers 👇🏼

© 2023 Flavio Copes Flavio Copes made in Italy 🇮🇹 using Notion to Site Notion to Site