2013-05-10 89 views
1

我想比較兩個日期字段..我已經得到了相當接近,它甚至能正常工作..比較日期字段

但是,當「TODATE」字段是

leap year>= "FromDate" 
問題就來了

對於如:

from date= 29/02/1996 
to date= 29/02/1996 
to date= 29/02/1992 
to date= 29/02/1995 

代碼工作很好..

但如果

from date= 29/03/1996 
to date= 29/02/1996 

代碼失敗......

這是我的代碼

function isDate(value) 
{ 
    var fromDate = document.getElementById("fromDate").value 
    var toDate= document.getElementById("toDate").value 
    var dateRegEx = null; 
    dateRegEx = new RegExp(/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g); 

    if (dateRegEx.test(fromDate)){ 
    } 
    else{ 
     alert("Invalid from date"); 
     return false; 
    } 
    dateRegEx = new RegExp(/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g); 
    if(dateRegEx.test(toDate)) { 
    } 
    else{ 
     alert("Invalid to date"); 
     return false; 
    } 
    var stDate = new Date(fromDate); 
    var enDate = new Date(toDate); 
    var compDate = enDate - stDate; 

    if(compDate > 0) 
     return true; 
    else 
    { 
     alert("Please Enter the correct date "); 
     return false; 
    } 
    /**/ 
} 

如何使所有閏年工作...在那裏我將不得不作出的代碼更改。

+0

Possibile重複:http://stackoverflow.com/questions/327429/whats-the-best-way-to-calculate-date-difference-in-javascript – 2013-05-10 12:11:55

+0

添加一個額外的條件來檢查閏年 – 999k 2013-05-10 12:15:26

+0

兩個日期領域單獨工作很好... – razor 2013-05-10 12:18:16

回答

2

這是一個外觀極好的jQuery插件做你想做什麼:http://momentjs.com/

+0

Upvote所有發貼到momentjs! – Codesleuth 2013-05-10 12:10:54

+0

雖然時刻是一個偉大的插件...... OP甚至沒有使用jQuery。 – jbabey 2013-05-10 12:11:32

+0

momentjs實際上並不是一個jQuery插件,所以這裏適合。 – Codesleuth 2013-05-10 12:15:01

1

下面是使用moment.js一個解決方案:

function isDate(value) 
{ 
    var fromDate = moment(document.getElementById("fromDate").value); 
    var toDate = moment(document.getElementById("toDate").value); 

    if (fromDate.isValid()) { 
    } 
    else { 
     alert("Invalid from date"); 
     return false; 
    } 

    if(toDate.isValid()) { 
    } 
    else { 
     alert("Invalid to date"); 
     return false; 
    } 

    if(toDate.isAfter(fromDate)) 
     return true; 
    else 
    { 
     alert("Please Enter the correct date "); 
     return false; 
    } 
} 

根據你的日期是如何表示,你可能必須提供的那一刻構造用另一個參數來表示格式。見Validation