Check if a Date is within 24 hours in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 24, 2022

banner

Photo from Unsplash

Check if a Date is within 24 hours in JavaScript #

To check if a date is within 24 hours:

  1. Subtract the timestamp of the current date from the timestamp of the date.
  2. Pass the result to the Math.abs() function.
  3. Convert the result to hours.
  4. Check if the hours between the dates are less than 24.
index.js
const then = new Date('2022-01-24T09:30:20'); const now = new Date(); const msBetweenDates = Math.abs(then.getTime() - now.getTime()); // 👇️ convert ms to hours min sec ms const hoursBetweenDates = msBetweenDates / (60 * 60 * 1000); console.log(hoursBetweenDates); if (hoursBetweenDates < 24) { console.log('date is within 24 hours'); } else { console.log('date is NOT within 24 hours'); }

The getTime method returns the number of milliseconds elapsed between the 1st of January 1970 and the given date.

We have to subtract the timestamp of the first date from the timestamp of the second date.

We used the Math.abs method to convert a possibly negative to a positive number.

The only parameter the function takes is the number we want to get the absolute value of.

The function returns the absolute value of a number, in other words it returns the number's distance from zero.

The Math.abs function returns the provided number if it's positive or zero and the negation of the number if it's negative.

index.js
console.log(Math.abs(-6)); // 👉️ 6 console.log(Math.abs(-6.5)); // 👉️ 6.5 console.log(Math.abs(-0)); // 👉️ 0

The msBetweenDates variable stores the number of milliseconds between the two dates.

The next step is to convert the milliseconds to hours.

Once we have the number of hours between the two days, all we have to do is check if the hours are less than 24 to see if the date is within 24 hours.

Note that this could mean that the date is within 24 hours in the future or 24 hours in the past.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.