PASSWORD RESET

Your destination for complete Tech news

How to check if a date is in the future in javascript?

4.32K 0
< 1 min read

You can check if a date is in the future 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 future:

// Create a new Date object for the given date
const givenDate = new Date('2024-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 future
if (givenDate.getTime() > currentDate.getTime()) {
  console.log('The given date is in the future.');
} else {
  console.log('The given date is not in the future.');
}

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 future, its getTime() value will be greater 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 future.” Otherwise, it will print “The given date is not in the future.”

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.