Introduction
Back in the day when JavaScript was introduced, it didn’t have any specific date
data type. But later, the date data type was introduced in JavaScript and that’s when developers started to look around for ways to compare dates in JavaScript.
If you are also looking for ways to compare different dates, you are at the right place. Besides that, even if you were just exploring the topic, it is recommended to go through this guide because at some point in your programming career as you will need to compare dates.
In this guide, I’m going to explain the simplest and most functional method to compare dates in JavaScript.
Simplest Method to Compare Dates
In order to compare dates, you have to convert the data type values to numerical values. You can do that using the built in method getTime()
.
getTime Method Definition
getTime()
returns the number of milliseconds since midnight, January 1, 1970, Coordinated Universal Time (UTC).
Refer to the MDN Docs for more information.
getTime Usage
Once you have successfully converted the dates values to numeric values, you can use the comparison operator such as >
, <
, etc.
Refer the script below for better understanding:
var date1 = new Date(2021 - 08 - 21);
var date2 = new Date(2020 - 09 - 21);
if (date1.getTime() > date2.getTime())
console.log("First date is greater than Second Date");
else if (date1.getTime() < date2.getTime())
console.log("First date is lesser than Second date");
else
console.log("Both the dates are same");
First date is greater than Second Date
In this example, only year, month and day was passed in both the variables. If you want, you can pass year, month, day, hour, minute, second as well. But beware of the format i.e., YY-MM-DD-Hr-Min-Sec
Refer the script below for more understanding:
var date1 = new Date(2021, 08, 21, 12, 15, 20); // Year, Month, Day, Hour, Minute, Second
var date2 = new Date(2020, 09, 21, 11, 23, 18); // September 21, 2020, 11:23:18 AM
if (date1.getTime() > date2.getTime())
console.log("First date is greater than Second date");
else if (date1.getTime() < date2.getTime())
console.log("Second Date is greater than First date");
else
console.log("Both the dates are same");
First date is greater than Second date
❗ Note: The time values are in millitary time ❗
Final Notes
In this guide, you have learned how to compare dates in JavaScript. Now, let's quickly recap everything that we have read so far.
- First, you need to convert the dates to numeric values.
- Secondly, you have to use the basic comparison operators to compare the numeric dates.
Based on the comparison, you can print the desirable output, or use the values however you want!