Borislav Hadzhiev
Tue Jan 25 2022·2 min read
Photo by Farsai Chaikulngamdee
To check if a date is before today's date:
Date()
constructor to create a new date.function isBeforeToday(date) { const today = new Date(); today.setHours(0, 0, 0, 0); return date < today; } const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); console.log(isBeforeToday(yesterday)); // 👉️ true console.log(isBeforeToday(tomorrow)); // 👉️ false console.log(isBeforeToday(new Date())); // 👉️ false
We created a reusable function that checks if the passed in date is before today's date.
The first thing we did in the function is use the Date() constructor to get the current date.
The
setHours
method takes the hours, minutes, seconds and milliseconds as parameters and
changes the values for the given Date
instance.
If you remove the line that uses the setHours()
method, you'd be checking if
the Date
is in the past and not necessarily yesterday or further removed.
The last step is to return the result of checking if the passed in date is less than today's date.
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-09-24'); // 👇️ 1663977600000 console.log(date.getTime());
getTime()
method on each date.If the passed in date is less than today's date, then it's in the past.