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.
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 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.
Once you have successfully converted the dates values to numeric values, you can use the comparison operator such as
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.,
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 ❗
- 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!
Written By Sumit Kumar