如何在JavaScript中检查一个日期是否指的是过去的某一天

74 阅读1分钟

给定一个JavaScript日期,如何检查它是否引用了过去的某一天?

发表于2019年10月16日,最后更新于2019年10月24日

我遇到了这样的问题:我想检查一个日期是否参考了过去的一天,与另一个日期相比。

仅仅使用getTime() 进行比较是不够的,因为日期可能有不同的时间。

我最后使用了这个函数。

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
}

我使用setHours() ,以确保我们在同一时间(00:00:00)比较两个日期。

这里是同样的函数,有隐含的返回,不那么臃肿

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

这里是如何用一个简单的例子来使用它,比较昨天和今天。

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

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

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