如何在JavaScript中确定日期是否为今天

How can you determine if a JavaScript Date object instance is a representation of a date/time that is “today”?

您如何确定JavaScript Date对象实例是否表示“今天”的日期/时间?

Given a Date instance, we can use the getDate(), getMonth() and getFullYear() methods, which return the day, month and year of a date, and compare them to today, which can be retrieved using new Date().

给定一个Date实例,我们可以使用getDate()getMonth()getFullYear()方法,它们返回日期的日,月和年,并将它们与今天进行比较,可以使用new Date()进行检索。

Here’s a small function that does exactly that, returning true if the argument is today.

这是一个精确执行此操作的小函数,如果参数为今天,则返回true。

const isToday = (someDate) => {
  const today = new Date()
  return someDate.getDate() == today.getDate() &&
    someDate.getMonth() == today.getMonth() &&
    someDate.getFullYear() == today.getFullYear()
}

You can use it like this:

您可以像这样使用它:

const today = isToday(myDate)

Check out the JavaScript Date guide to find out more how to handle the Date object, if you need.

如果需要,请查看JavaScript日期指南,以了解更多有关如何处理Date对象的信息。

翻译自: https://flaviocopes.com/how-to-determine-date-is-today-javascript/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值