In this article, we will compare the 2 dates in Javascript, along with understanding their implementation through the examples.
In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.
Example 1: This example illustrates the comparison of the dates using the getTime() function.
javascript
<script>
var g1 = new Date();
var g2 = new Date();
if (g1.getTime() === g2.getTime())
document.write( "Both are equal" );
else
document.write( "Not equal" );
javascript: ;
</script>
|
Output:
Both are equal
Example 2: This example illustrates the comparison of the current date with the assigned date using the getTime() function.
Javascript
<script>
var g1 = new Date();
var g2 = new Date(2019 - 08 - 03);
if (g1.getTime() < g2.getTime())
document.write( "g1 is lesser than g2" );
else if (g1.getTime() > g2.getTime())
document.write( "g1 is greater than g2" );
else
document.write( "both are equal" );
</script>
|
Output:
g1 is greater than g2
Example 3: This example illustrates the comparison of 2 given dates using the getTime() function.
Javascript
<script>
var g1 = new Date(2019, 08, 03, 11, 45, 55);
var g2 = new Date(2019, 08, 03, 10, 22, 42);
if (g1.getTime() < g2.getTime())
document.write( "g1 is lesser than g2" );
else if (g1.getTime() > g2.getTime())
document.write( "g1 is greater than g2" );
else
document.write( "both are equal" );
</script>
|
Output:
g1 is greater than g2
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
23 Nov, 2021
Like Article
Save Article