Skip to content
Related Articles

Related Articles

Compare two dates using JavaScript
  • Last Updated : 15 Apr, 2019

In JavaScript, we can compare two dates by converting them into numeric value to corresponding to its time. First, we can convert the Date into a numeric value by using getTime() function. By converting the given dates into numeric value we can directly compare them.

Example-1:




<script>
    // Current Date
    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:




<script>
    var g1 = new Date();
    // (YYYY-MM-DD)
    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");
  
javascript: ; 
</script>

Output:

g1 is greater than g2

Example-3:




<script>
    var g1 = new Date(2019, 08, 03, 11, 45, 55);
    // (YYYY, MM, DD, Hr, Min, Sec)
    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");
  
javascript: ; 
</script>

Output:

g1 is greater than g2



My Personal Notes arrow_drop_up
Recommended Articles
Page :