Compare two dates in JavaScript
In this article, we will explain to you the best way to compare two dates in javascript and give you a simple guide that will help you to get the results as you expected.
Compare two string dates in JavaScript, Comparing two dates with JavaScript, Comparison between two dates, Checking Date Equality in JavaScript, compare two dates in javascript dd mm yyyy, compare date with current date in javascript, javascript compare date strings, javascript compare dates without time, how to check two dates are equal in javascript, angular 2 compare date with current date, javascript compare dates with time, compare two dates in jquery.
Checkout more articles on JavaScript
- Spread Operator in JavaScript
- Rest Parameters in JavaScript
- Replace all occurrences of a string in JavaScript
- url-in-javascript" title="Get Current URL in JavaScript">Get Current URL in JavaScript
To compare the values of two dates, we need to check the first date is greater, less or equal than the second date. Using the Date object we can compare dates in JavaScript.
Different ways to compare two dates in JavaScript
1. Compare two dates without time
Here, we will learn to compare dates using `new Date()` operators that creates a new date object with the current date and time. Assume that, we have two JavaScript Date objects like:
var date1 = new Date("2018-04-17");
var date2 = new Date("2019-03-28");
if (date1 > date2) {
console.log("date1 is greater than date2");
} else if (date1<date2) {
console.log("date1 is less than date2");
} else {
console.log("date1 is equal to date2");
}
// Output: date1 is less than date2
2. Compare dates with time
Let's see another example to compare dates with time.
var date1 = new Date("Apr 17, 2018 19:15:50");
var date2 = new Date("Mar 28, 2019 18:36:41");
if (date1 > date2) {
console.log("date1 is greater than date2");
} else if (date1 < date2) {
console.log("date1 is less than date2");
} else {
console.log("date1 is equal to date2");
}
// Output: date1 is less than date2
3. Compare dates Using getTime() function
Now we’ll see the example to compare dates using `getTime()` function that returns the number of milliseconds.
We recommend that, comparing dates using getTime() function is good practice instead of comparing dates using new date() operator. Here we compare the date with current date.
var currentDate = new Date();
var date = new Date("Mar 28, 2019 18:36:41");
if (currentDate.getTime() > date.getTime()) {
console.log("currentDate is greater than date");
} else if (currentDate.getTime() < date.getTime()) {
console.log("currentDate is less than date");
} else {
console.log("currentDate is equal to date");
}
// Output: currentDate is greater than date
Thank you for reading! Happy Coding..!!