Borislav Hadzhiev
Wed Jan 26 2022·2 min read
Photo by Daria Nepriakhina
To check if a date is less than 1 hour ago:
function isLessThan1HourAgo(date) { // 👇️ min sec milliseconds const hourInMilliseconds = 60 * 60 * 1000; const oneHourAgo = Date.now() - hourInMilliseconds; return date > oneHourAgo; } console.log(isLessThan1HourAgo(new Date())); // 👉️ true console.log(isLessThan1HourAgo(new Date('2022-01-25'))); // 👉️ false
We created a reusable function that takes a Date
object as a parameter and
checks if the date is less than 1 hour ago.
true
for dates in the future. If you only want to check if the Date is less than 1 hour ago and is NOT in the future, scroll down to the next code snippet.The first step is to calculate how many milliseconds there are in an hour.
The Date.now() method returns the number of milliseconds elapsed since midnight of the 1st of January 1970.
By subtracting 1
hour in milliseconds from the timestamp, we get the moment in
time 1 hour ago.
We are able to compare the date to a timestamp 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 you need to check if a date is less than 1 hour ago and is not in the future, add a condition that checks that the date is less than or equal to the current timestamp.
function isLessThan1HourAgo(date) { // 👇️ min sec milliseconds const hourInMilliseconds = 60 * 60 * 1000; const oneHourAgo = Date.now() - hourInMilliseconds; return date > oneHourAgo && date <= Date.now(); } console.log(isLessThan1HourAgo(new Date())); // 👉️ true console.log(isLessThan1HourAgo(new Date('2035-01-29'))); // 👉️ false
The second condition would not be met for any dates in the future.
The logical AND (&&) operator will only return true
if both conditions are
met, otherwise false
is returned.