2014-06-24 66 views
0

我有下面的Java腳本代碼,將驗證日期範圍...當用戶輸入今天的日期或任何未來的日期我已經將IsValid設置爲true,然後將執行保存操作....JavaScript日期驗證不適用於今天的日期

爲此我寫了下面的代碼..

function Save(e) { 
    var popupNotification = $("#popupNotification").data("kendoNotification"); 

    var container = e.container; 
    var model = e.model; 

    var isValid = true; 
    var compareDate = e.model.DeliveryDate; 
    alert(compareDate); 
    var todayDate = new Date(); 
    var compareDateModified = new Date(compareDate) 
    alert(compareDateModified); 
    if (compareDateModified > todayDate || compareDateModified === todayDate) { 
     isValid = true; 

    } 
    else 
     isValid = false; 
    e.preventDefault(); 
    if (isValid == false) 
    { 

     popupNotification.show("Delivery Date should be today date or Greater", "error"); 

    } 
    $('#Previous').show(); 
    $('#Next').show(); 
} 

其工作正常,當我給將來的日期,但它不工作爲今天的日期。我還需要檢查今天的日期。當我嘗試輸入今天的日期時,我無法找出錯誤提示。

回答

1

認爲日期對象就像一個時間戳。它基於unix樣式的時間戳(自1970年1月1日以來的秒數),所以Date對象不是一天,而是Date和Time。

你正在比較的是時間,這可能會有點不妥。如果只有幾天的事情,請嘗試使用:

fullCompareDate = compareDateModified.getFullYear() + "/" + compareDateModified.getMonth() + "/" + compareDateModified.getDate(); 
fullTodayDate= todayDate.getFullYear() + "/" + todayDate.getMonth() + "/" + todayDate.getDate(); 
if(compareDateModified>todayDate||fullCompareDate==fullTodayDate) 
{ 
    //Do something 
} 

這將比較的日期和時間,以確保它們是大於或檢查當前的日期比較日期(字符串)

另一個解決方案是空白出兩個日期時間:

compareDateModified.setHours(0,0,0,0); 
todayDate.setHours(0,0,0,0); 
if(compareDateModified>=todayDate) 
{ 
    //Do something 
} 
+0

非常感謝它現在的工作..... –

2

你比較兩個同類型的對象,但不同的對象,這樣就總是導致「不平等」 如果使用date.getTime(),您將得到更好的導致你的比較 - 但只有在t ime組件當然是相同的。

1

您正在比較compareDateModified與todayDate的毫秒級別。要比較一天的水平:

var todayDate = new Date(); 
todayDate.setHours(0,0,0,0); 
//you may also have to truncate the compareDateModified to the first 
//second of the day depending on how you setup compareDate 
if (compareDateModified >= todayDate) { 
    isValid = true; 
} 
+0

非常感謝...... –