How to check if a date is older than one month or 30 days in JavaScript:
In this post, we will learn how to check if a date is older than one month or not in JavaScript. The program will take one Date value and it will print one message if it is before 30 days or not.
We will use getTime method, which is an inbuilt method of JavaScript Date. Let me give you an introduction to getTime() before we move to the main example.
getTime():
getTime() method returns the number of milliseconds since Epoch time. It is the time in milliseconds from 1 January 1970 00:00:00 UTC.
So, if we find the difference between current Date’s getTime and previous Date’s getTime, we can find the difference is more than milliseconds of 30 days or not.
JavaScript program to check if a date is older than one month:
Below is the complete JavaScript program:
const pastTime = new Date('2000-08-22');
const now = new Date();
const thirtyDaysInMs = 30 * 24 * 60 * 60 * 1000;
const timeDiffInMs = now.getTime() - pastTime.getTime();
if(timeDiffInMs >= thirtyDaysInMs){
console.log('Date is older than 30 days');
}else{
console.log('Date is not older than 30 days');
}
Here,
- pastTime is a Date object of a past date-time.
- now is a Date object of current date-time.
- thirtyDaysInMs is the total milliseconds of 30 days.
- timeDiffInMs is time difference in milliseconds between current time and past time.
- The if block is checking if the time difference is greater than or equal to thirty days in milliseconds and prints one message based on that.
You can try this example by changing the pastTime.
You might also like:
- JavaScript Map forEach method example
- How to add one second delay in JavaScript
- JavaScript example to add padding to the end of a string using padEnd
- JavaScript Array every method explanation with example
- JavaScript program to check if an array is a subarray of another array
- JavaScript program to delete an item from a set
- JavaScript set add() method explanation with example