Categories
JavaScript Answers

How to check if date is in the past in JavaScript?

Spread the love

Sometimes, we want to check if date is in the past in JavaScript.

In this article, we’ll look at how to check if date is in the past in JavaScript.

How to check if date is in the past in JavaScript?

To check if date is in the past in JavaScript, we get the difference of the timestamp between the current date time and the given date.

For instance, we write

const diff = new Date().getTime() - givenDate.getTime();
if (diff > 0) {
  console.log("givenDate is in the past");
}

to call getTime to get the timestamp of each datetime in milliseconds.

Then we get their difference and assign it to diff1.

If diff is bigger than 0, then givenDate is in the past.

Conclusion

To check if date is in the past in JavaScript, we get the difference of the timestamp between the current date time and the given date.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *