Skip to content
Related Articles

Related Articles

Improve Article

Compare two dates using JavaScript

  • Last Updated : 21 Jul, 2021
Geek Week

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

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.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :