Borislav Hadzhiev
Mon Jan 24 2022·2 min read
Photo by Raychan
To check if a date is more than 30 days from today's date:
// ✅ 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.
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:
30
days ago.30
days ago is greater than the date's timestamp.30
days into the past.If you need to check if a given date is more than 30
days into the future:
30
days into the future.30
days into the future.30
days into the future.