How to check 2 date fields and compare to see which date is ahead, behind or the same

前端 未结 3 911
清酒与你
清酒与你 2021-01-26 11:00

I\'m working with 2 dates that are posted back to me in a textbox as strings in this format 03/02/2010. One is the current completion date and the second is the final completion

相关标签:
3条回答
  • 2021-01-26 11:35
    var passedDate1 = new Date('03/02/2010');
    var passedDate2 = new Date('03/01/2010');
    
    if (passedDate1 > passedDate2) {
       alert ('Date1 is greated than date 2');
    }
    else if (passedDate1 < passedDate2) {
       alert ('Date1 is less than date 2');
    }
    else {
       alert ('they are equal');
    }
    
    0 讨论(0)
  • 2021-01-26 11:36
    var doc = document,
    dateBox1 = doc.getElementById("date1").value,
    dateBox2 = doc.getElementById("date2").value,
    d1, d2, diff;
    
    //if there is no value, Date() would return today
    if (dateBox1) {
        d1 = new Date(dateBox1);
    } else {
        //however you want to handle missing date1
    }
    if (dateBox1) {
        d2 = new Date(dateBox2);
    } else {
        //however you want to handle missing date2
    }
    if (d1 && d2) {
        //reduce the difference to days in absolute value
        diff = Math.floor(Math.abs((d1 - d2) /1000/60/60/24 ));
    } else {
        //handle not having both dates
    }
    if (diff === 0) {
        //d1 and d2 are the same day
    }
    if (diff && d1 > d2) {
        //d1 is diff days after d2 and the diff is not zero
    }
    if (diff && d1 < d2) {
        //d1 is diff days before d2 and the diff is not zero
    }
    
    0 讨论(0)
  • 2021-01-26 11:38

    Convert it to US format

    function dateUS(date)
    {
        var date = date.split("/");
        return date[2] + '/' + date[1] + '/' + date[0];
    }
    

    and then

    if(dateUS(dateCurrent) < dateUS(dateFinal))
    {
      //your code
    }
    
    0 讨论(0)
提交回复
热议问题