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.
仅使用getTime()
比较它们是不够的,因为日期可能具有不同的时间。
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).
我使用setHours()
来确保我们同时比较两个日期(00:00:00)。
Here is the same function with the implicit return, less bloated
这是具有隐式返回的相同功能,但不那么blo肿
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
翻译自: https://flaviocopes.com/how-to-check-date-is-past-javascript/