You can check if a date is in the past in JavaScript by comparing it with the current date using the Date
object. Here is an example code snippet that checks if a given date is in the past:
// Create a new Date object for the given date
const givenDate = new Date('2022-01-01');
// Get the current date
const currentDate = new Date();
// Compare the two dates using getTime() method and check if the given date is in the past
if (givenDate.getTime() < currentDate.getTime()) {
console.log('The given date is in the past.');
} else {
console.log('The given date is not in the past.');
}
In this example, we first create a new Date
object for the given date. Then we create another Date
object for the current date using the Date()
constructor without any arguments, which creates a Date
object for the current date and time.
We compare the two dates using the getTime()
method, which returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. If the given date is in the past, its getTime()
value will be less than the current date’s getTime()
value, and the condition givenDate.getTime() < currentDate.getTime()
will be true, so the code will print “The given date is in the past.” Otherwise, it will print “The given date is not in the past.”