2013-04-01 57 views
2

我想通過日期比較jQuery中的一些消息。 例如: 我有一個文本框值爲04/01/2013 13:15:32由userend填充。 而在jQuery的變量中的當前日期時間爲04/01/2013 18:30:12 如果文本框值小於當前日期時間,然後顯示一個消息:在jQuery中比較日期和時間

function foo(){ 
    usrDate = jQuery("#txtDate").val(); //getting user input date time 

    currentDate = new Date(); //system current date 
    currentMonth = currentDate.getMonth() + 01; 
    currentDay = currentDate.getDate(); 
    currentYear = currentDate.getFullYear(); 
    currentHours = currentDate.getHours(); 
    currentMinutes = currentDate.getMinutes(); 
    currentSeconds = currentDate.getSeconds(); 

    currentcpDateTime = currentMonth + "/" + currentDay + "/" + currentYear + " " + currentHours + ":" + currentMinutes + ":" + currentSeconds; 
     if (usrDate > currentcpDateTime) { 
     alert("you can not choose date greater then current"); 
    } 
    else { 
     alert("valid date"); 
} 
} 

每一次錯誤的結果。 :(

+0

當您應該比較日期對象時,您正在比較字符串。基本上你是在倒退,因爲你應該把'usrDate'字符串轉換成日期對象,而不是將'current ****'中的日期對象轉換爲字符串。 – adeneo

+0

爲什麼不使用普通的javascript?使用'gettime()'函數將日期轉換爲刻度,然後您可以比較兩個數字。 –

+0

使用'if(Date.parse(usrDate)> Date.parse(currentcpDateTime))' –

回答

3

爲什麼不使用像jQuery UI的框架,你可以這樣做簡單,如下

你的HTML

<p>Date: <input type="text" id="datepicker" /></p> 
<input type="button" id="checkDate" value="CheckDate"> 

你的JS

$(document).ready(function(){ 
    $("#datepicker").datepicker(); 
    $('#checkDate').bind('click',function(){ 
     var myDAte = $('#datepicker').datepicker("getDate"); 
     var curDate = new Date(); 

     if(curDate>myDAte){ 
      alert('current date is high'); 
     } 
     else{ 
      alert('selected date is high'); 
     } 
    }); 
}); 

退房在的例子Live fiddle

+0

實際上,我在檢查這些條件之前在當前日期時間中添加了幾個小時。 –

+0

你可以[添加小時](http://stackoverflow.com/questions/1050720/adding-hours-to-javascript-date-object)到你的日期對象。所以我不認爲它是一個問題。 –