Check if Date is more than 30 days from today's date in JS

avatar

Borislav Hadzhiev

Last updated: Jan 24, 2022

banner

Photo from Unsplash

Check if Date is more than 30 days from today's date in JS #

To check if a date is more than 30 days from today's date:

  1. Get a timestamp representing a date 30 days in the past or future.
  2. Compare the result to the timestamp for the specific date.
index.js
// ✅ Check if date is more than 30 days AGO function isMoreThan30DaysAgo(date) { // days hours min sec ms const thirtyDaysInMs = 30 * 24 * 60 * 60 * 1000; const timestampThirtyDaysAgo = new Date().getTime() - thirtyDaysInMs; if (timestampThirtyDaysAgo > date) { console.log('date is more than 30 days into the past'); return true; } else { console.log('date is NOT more than 30 days into the past'); return false; } } // 👇️ true console.log(isMoreThan30DaysAgo(new Date('2021-09-24'))); // 👇️ false console.log(isMoreThan30DaysAgo(new Date('2021-12-26'))); // ✅ Check if date is more than 30 days IN THE FUTURE function isMoreThan30DaysInFuture(date) { // days hours min sec ms const thirtyDaysInMs = 30 * 24 * 60 * 60 * 1000; const timestampThirtyDaysInFuture = new Date().getTime() + thirtyDaysInMs; if (date > timestampThirtyDaysInFuture) { console.log('date is more than 30 days into the future'); return true; } else { console.log('date is NOT more than 30 days into the future'); return false; } } // 👇️ true console.log(isMoreThan30DaysInFuture(new Date('2029-04-25'))); // 👇️ false console.log(isMoreThan30DaysInFuture(new Date('2022-02-23')));

We calculated the number of milliseconds there are in 30 days.

The getTime() method returns the number of milliseconds since the Unix Epoch.

Calling the method on a Date object that represents the current date gets us the number of milliseconds elapsed between the 1st of January 1970 and the current date.

If we subtract the number of milliseconds there are in 30 days, we get a timestamp that represents a date and time exactly 30 days ago.

Similarly, if we add the number of milliseconds there are in 30 days to the current timestamp, we get a date that is 30 days in the future.

If you need to check if a given date is more than 30 days into the past:

  • get a timestamp of the date 30 days ago.
  • check if the timestamp of 30 days ago is greater than the date's timestamp.
  • if it is, the date is more than 30 days into the past.

If you need to check if a given date is more than 30 days into the future:

  • get a timestamp of the date 30 days into the future.
  • check if the passed in date is greater than the timestamp of the date 30 days into the future.
  • if it is, the date is more than 30 days into the future.
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.