Skip to content

JavaScript Date comparison | String, time, Operators

  • by

You can do JavaScript Date comparison by operators and require to use date.getTime(). The getTime() function converts the given date objects into the numeric value we can directly compare them.

Examples of JavaScript Date comparison

The Date object will construct one for each date, then compare them using the ><<= or >=.

The ==!====, and !== operators require you to use date.getTime().

Compare 2 Dates in JS

<!DOCTYPE html> 
<html> 
    <body> 
    	
<script> 
    // Current Date 
    var d1 = new Date('Aug 04 2020'); 
    var d2 = new Date('Aug 04 2020'); 
    if (d1.getTime() === d2.getTime()) 
        alert("Both  are equal"); 
    else
        document.write("Not equal");  
</script> 


    </body> 
</html>   

Output:

JavaScript Date comparison

Compare date with the current date in javascript

Given string will take automatic time on converting in date object. So Current date will be greater in below example.

<!DOCTYPE html> 
<html> 
    <body> 
    	
	<script>

	var d = new Date();

	mydate=new Date('2020-08-04');
	console.log(d);
	console.log(mydate)

	if(d>mydate)
	{
    	alert("greater");
	}
	else
	{
   	 alert("smaller")
	}

</script>


    </body> 
</html>

Output:

How to JavaScript date comparison without time?

Do not want to check the time part of the two dates, you can get the date part alone from dates and compare it?

Do clearing the time using Date.setHours:

dateObj.setHours(hoursValue[, minutesValue[, secondsValue[, msValue]]])

Complete Example code

<!DOCTYPE html> 
<html> 
    <body> 
    	
	<script>

		var today = new Date();
		today.setHours(0, 0, 0, 0);
		mydate=new Date('2021-08-04');
		mydate.setHours(0, 0, 0, 0);

	if(mydate >= today){ 
    alert('mydate is greater than or equal to current date');
	}

</script>


    </body> 
</html>   

Output: mydate is greater than or equal to current date

How to javascript compare date strings?

var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
    alert ("Error!");
}

Do comment if you have any suggestions or doubts on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *