Compare two dates using JavaScript

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output:



Both are equal

Example-2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output:

g1 is greater than g2

Example-3:

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output:

g1 is greater than g2


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.