In this article, you will learn how to compare two dates in javascript. Date comparison is required any time you are using Date in your code or program. You can create the new Date
objects using the Date()
Constructor. You can compare two dates with JavaScript, you compare them using the >, <, <= or >= operators.
This article will help you to resolve the following problems:
Note: In Javascript, the month value will start from 0 to 11. In other words, 0 means January, 1 means February, 2 means March, and so on.
In this example, we create two new same dates with different times.
// Compare two Dates with Time in Javascript
function CompareDate() {
// create new date using Date Object => new Date(Year, Month, Date, Hr, Min, Sec);
var firstOne = new Date(2021, 04, 20, 14, 55, 59);
var secondTwo = new Date(2021, 04, 20, 12, 10, 20);
//Note: 04 is month i.e. May
if (firstOne > secondTwo) {
alert("First Date is greater than Second Date.");
} else {
alert("Second Two is greater than First Date.");
}
}
CompareDate();
In this example, we create two dates, today’s date and or another one is any random date, and compare these two dates.
// Compare Today's date with another Date
function CompareDate() {
var todayDate = new Date(); //Today Date
var anyDate = new Date(2020, 11, 25);
if (todayDate > anyDate) {
alert("Today's Date is greater than other given Date.");
} else {
alert("Today's Date is smaller than other given Date.");
}
}
CompareDate();
In this example, we create two dates and compare these dates.
//Compare Two Dates in Javascript
function CompareDate() {
//Note: 00 is month i.e. January
var firstDate = new Date(2020, 3, 15); //Year, Month, Date
var secondDate = new Date(2021, 3, 15); //Year, Month, Date
if (firstDate > secondDate) {
alert("First Date is greater than Second Date.");
} else {
alert("Second Date is greater than First Date.");
}
}
CompareDate();
I hope this article will help you to understand how to compare two dates in javascript.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments