Sometimes, we want to check if a date is today with JavaScript.
In this article, we’ll look at how to check if a date is today with JavaScript.
How to check if a date is today with JavaScript?
To check if a date is today with JavaScript, we can convert both dates to date strings before doing the comparison.
For instance, we write:
const today = new Date()
const today2 = new Date(2022, 0, 20)
const isSame = today.toDateString() === today2.toDateString();
console.log(isSame)
We create 2 Date
instances, today
and today2
.
Then we call toDateString
on both of them to convert them to date strings.
Then we can use ===
to compare the date strings.
If today
is January 20, 2022, then isSame
would be true
.
Conclusion
To check if a date is today with JavaScript, we can convert both dates to date strings before doing the comparison.