Check if a Date is within 30 days in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 24, 2022

banner

Photo from Unsplash

Check if a Date is within 30 days in JavaScript #

To check if a date is within 30 days:

  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 days.
  4. Check if the days between the dates is less than 30.
index.js
const then = new Date('2022-01-21'); const now = new Date(); const msBetweenDates = Math.abs(then.getTime() - now.getTime()); // 👇️ convert ms to days hour min sec ms const daysBetweenDates = msBetweenDates / (24 * 60 * 60 * 1000); if (daysBetweenDates < 30) { console.log('date is within 30 days'); } else { console.log('date is NOT within 30 days'); }

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 function 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(-3)); // 👉️ 3 console.log(Math.abs(-3.5)); // 👉️ 3.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 days.

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

Note that this could mean that the date is within 30 days in the future or 30 days 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.