Sometimes, we want to check whether the date entered by the user is current date or the future date with JavaScript.
In this article, we’ll look at how to check whether the date entered by the user is current date or the future date with JavaScript.
How to check whether the date entered by the user is current date or the future date with JavaScript?
To check whether the date entered by the user is current date or the future date with JavaScript, we can set the time to midnight on each date and compare them.
For instance, we write:
const inFuture = (date) => {
return date.setHours(0, 0, 0, 0) > new Date().setHours(0, 0, 0, 0)
};
console.log(inFuture(new Date(2029, 1, 1)))
console.log(inFuture(new Date(2019, 1, 1)))
to define the inFuture
function that takes a date
.
In the function, we call setHours
with all 0’s to set the dates to midnight of the same date.
Then we check if date
is bigger than new Date()
to check if date
is in the future.
Therefore, if today is January 21, 2022, then the first console log is true
and the 2nd log is false
.
Conclusion
To check whether the date entered by the user is current date or the future date with JavaScript, we can set the time to midnight on each date and compare them.