ADVERTISEMENT
ADVERTISEMENT

Compare two dates with JavaScript

JavaScript | Comparing dates: Given two dates, we have to compare them.
Submitted by Pratishtha Saxena, on May 25, 2022

Here, we will discuss two methods to compare the dates in JavaScript.

1) Using Comparison Operators

This is the most basic and simplest way of comparing dates. Here, the dates are compared with the help of various comparison operators like >, <, etc.

Firstly, the date object is created using the Date() constructor. It is then compared. It can compare two current dates, past date and current date, future date and past date, etc.

Syntax:

DateObjectOne > DateObjectTwo

Example 1:

function CompareDates() {
	var DateOne = new Date(2019, 02, 14); //(YYYY-MM-DD)
	var DateTwo = new Date(2011, 05, 7); //(YYYY-MM-DD)

	if (DateOne > DateTwo) {
		console.log("Date One is greater than Date Two.");
	} else {
		console.log("Date Two is greater than Date One.");
	}
}
CompareDates();

Output:

Date One is greater than Date Two.

2) Using getTime() Method

If we have to compare and check which date is greater, then another way of doing this is by using the getTime() method of JavaScript.

This method basically returns the numeric value of the date specified. The getTime() converts the date into the number of milliseconds passed since ECMAScript epoch. We can then easily compare this numeric value and find which one is greater.

Syntax:

dateObject.getTime()

Example 2:

var Date_1 = new Date();
var Date_2 = new Date(2021 - 07 - 15); // (YYYY-MM-DD)

if (Date_1.getTime() < Date_2.getTime())
	console.log("Date_1 is lesser than Date_2");

else if (Date_1.getTime() > Date_2.getTime())
	console.log("Date_1 is greater than Date_2");

else
	console.log("both are equal");

Output:

Date_1 is greater than Date_2

JavaScript Examples »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.