Q:

How to Compare Two Dates in JavaScript

0

How to Compare Two Dates in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the getTime() Method

You can simply use the getTime() method to compare two dates in JavaScript. This method returns the number of milliseconds since the ECMAScript epoch (January 1, 1970 at 00:00:00 UTC).

Let's take a look at the following example to understand how it basically works:

// Sample dates
var date1 = new Date("August 15, 1994");
var date2 = new Date("December 10, 2022 04:30:00");
var date3 = new Date("2022-12-10T04:30:00");

// Performing comparison
console.log(date1.getTime() == date2.getTime()); // Prints: false
console.log(date1.getTime() == date3.getTime()); // Prints: false
console.log(date2.getTime() == date3.getTime()); // Prints: true
console.log(date2.getTime() != date3.getTime()); // Prints: false
console.log(date1.getTime() > date2.getTime());  // Prints: false
console.log(date1.getTime() < date2.getTime());  // Prints: true
console.log(date1.getTime() != date2.getTime()); // Prints: true

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Convert a Unix Timestamp to Time in JavaScr... >>
<< How to Add Days to Current Date in JavaScript...