JavaScript Program to Compare The Value of Two Dates

To understand this example, you should have the knowledge of the following JavaScript programming topics:


Example: Compare Value of Two Dates

Output

false
false
true
true
true
false

In the above example, the new Date() constructor is used to create a date object.

The new Date() gives the current date and time.

const d1 = new Date();
console.log(d1); // Fri Aug 28 2020 09:19:40 GMT+0545 (+0545)

You can then directly compare these two dates using comparison operators >, <, <=, or >=.

However, to use comparison operators like ==, !=, ===, or !==, you have to use date.getTime().

The getTime() method returns the number of milliseconds from midnight of January 1, 1970 (EcmaScript epoch) to the specified date.

const d1 = new Date().getTime();
console.log(d1); // 1598585951699