Check if a Date is within 24 hours in JavaScript

Borislav Hadzhiev

Last updated: Jan 24, 2022

Photo from Unsplash

**To check if a date is within 24 hours:**

- Subtract the timestamp of the current date from the timestamp of the date.
- Pass the result to the
`Math.abs()`

function. - Convert the result to hours.
- 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.