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/