Borislav Hadzhiev
Wed Jan 26 2022·2 min read
Photo by Francisco Moreno
To check if a date is in the future:
Date()
constructor to get the current date.function isInTheFuture(date) { const today = new Date(); // 👇️ OPTIONAL! // This line sets the time of the current date to the // last millisecond, so the comparison returns `true` only if // date is at least tomorrow today.setHours(23, 59, 59, 998); return date > today; } const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); console.log(isInTheFuture(tomorrow)); // 👉️ true console.log(isInTheFuture(new Date('2021-01-25'))); // 👉️ false
We created a reusable function that takes a DAte
object as a parameter and
checks if the date is in the future.
The first thing we did is use the
Date()
constructor to create a Date
object that represents the current date.
The next line uses the setHours method to set the hour, minutes, seconds and milliseconds of the date to the last millisecond of the current date.
This line is optional and enables us to check if the passed in Date
is at
least tomorrow's date.
Here is the same example without setting the hour, minutes, seconds and milliseconds to the last millisecond of the current date.
function isInTheFuture(date) { const today = new Date(); return date > today; } const oneHourInTheFuture = new Date(); oneHourInTheFuture.setHours(oneHourInTheFuture.getHours() + 1); console.log(isInTheFuture(oneHourInTheFuture)); // 👉️ true console.log(isInTheFuture(new Date('2021-01-25'))); // 👉️ false
We are able to compare the dates because under the hood each date stores a timestamp - the number of milliseconds elapsed between the 1st of January 1970 and the given date.
const date = new Date('2022-10-26'); // 👇️ 1666742400000 console.log(date.getTime());
getTime()
method on each date.