2011-11-29 144 views
37

全部, 我爲日期選取器使用jQuery UI。我試圖用javascript來檢查,但用戶輸入的日期是過去的。這裏是我的表單代碼:檢查日期是否過去Javascript

<input type="text" id="datepicker" name="event_date" class="datepicker"> 

那麼我將如何使用JavaScript檢查是爲了確保它不是過去的日期?由於

回答

92

$('#datepicker').datepicker().change(evt => { 
 
    var selectedDate = $('#datepicker').datepicker('getDate'); 
 
    var now = new Date(); 
 
    now.setHours(0,0,0,0); 
 
    if (selectedDate < now) { 
 
    console.log("Selected date is in the past"); 
 
    } else { 
 
    console.log("Selected date is NOT in the past"); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> 
 
<input type="text" id="datepicker" name="event_date" class="datepicker">

+2

你的意思'變種現在=新的日期()'和'new'後的空間? – jfriend00

+0

這很好,謝謝。 – user1048676

+6

單行:'if($('#datepicker')。datepicker('getDate') davidchambers

-3
function isPrevDate() { 
    alert("startDate is " + Startdate); 
    if(Startdate.length != 0 && Startdate !='') { 
     var start_date = Startdate.split('-'); 
     alert("Input date: "+ start_date); 
     start_date=start_date[1]+"/"+start_date[2]+"/"+start_date[0]; 
     alert("start date arrray format " + start_date); 
     var a = new Date(start_date); 
     //alert("The date is a" +a); 
     var today = new Date(); 
     var day = today.getDate(); 
     var mon = today.getMonth()+1; 
     var year = today.getFullYear(); 
     today = (mon+"/"+day+"/"+year); 
     //alert(today); 
     var today = new Date(today); 
     alert("Today: "+today.getTime()); 
     alert("a : "+a.getTime()); 
     if(today.getTime() > a.getTime()) 
     { 
      alert("Please select Start date in range"); 
      return false; 
     } else { 
      return true; 
     } 
    } 
} 
+1

其中var Startdate來自哪裏? –

3
var datep = $('#datepicker').val(); 

if(Date.parse(datep)-Date.parse(new Date())<0) 
{ 
    // do something 
}