Compare two dates with JavaScript

Compare two dates with JavaScript

Asked on November 28, 2018 in Javascript.
Add Comment


  • 3 Answer(s)

    This one is pretty simple,  follow these steps.

    construct one date object for each date, then by using the >, <, <= or >=  operators for compare them .

    These following operators require you to use date.getTime(). They are ==, !=, ===, and !== operators as in,

    var d1 = new Date();
    var d2 = new Date(d1);
    var same = d1.getTime() === d2.getTime();
    var notSame = d1.getTime() !== d2.getTime();
    

    checking for equality directly with the data objects won’t work.

    var d1 = new Date();
    var d2 = new Date(d1);
     
    console.log(d1 == d2); // prints false (wrong!)
    console.log(d1 === d2); // prints false (wrong!)
    console.log(d1 != d2); // prints true (wrong!)
    console.log(d1 !== d2); // prints true (wrong!)
    console.log(d1.getTime() === d2.getTime()); // prints true (correct)
    

    Instead of text boxes, we always try to use something named drop-downs or some similar constrained form of date entry.

    Answered on November 28, 2018.
    Add Comment

    Try to do this, its will be simple for you,when you compare < and > is usual thats fine. but anything involved = should use a + prefix

    var x = new Date('2013-05-23');
    var y = new Date('2013-05-23');
     
    // less than, greater than is fine:
    x < y; => false
    x > y; => false
    x === y; => false, oops!
     
    // anything involving '=' should use the '+' prefix
    // it will then compare the dates' millisecond values
    +x <= +y; => true
    +x >= +y; => true
    +x === +y; => true
    
    Answered on November 28, 2018.
    Add Comment

    Actually, we have a easiest method ever, which is compare the results. we have to subtract datas and compare the results.

    var oDateOne = new Date();
    var oDateTwo = new Date();
    
    alert(oDateOne - oDateTwo === 0);
    alert(oDateOne - oDateTwo < 0);
    alert(oDateOne - oDateTwo > 0);
    
    Answered on November 28, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.