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

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值