How to check if the date points to the past day in JavaScript

Given a JavaScript date, how can I check if it refers to a day in the past?

I ran into this problem: I want to check whether a date refers to the past day and not another date.

Just use to compare themgetTime()This is not enough, because the date may have a different time.

I ended up using this feature:

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 usesetHours()Make sure we compare two dates (00:00:00) at the same time.

This is the same function with implicit return, but not so bloated

const firstDateIsPastDayComparedToSecond = (firstDate, secondDate) => firstDate.setHours(0,0,0,0) - secondDate.setHours(0,0,0,0) < 0

Here is a simple example that compares yesterday with today:

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

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

firstDateIsPastDayComparedToSecond( yesterday, today) //true firstDateIsPastDayComparedToSecond( today, yesterday) //false

Download mine for freeJavaScript beginner's manual


More js tutorials: