全部, 我正在使用jQuery UI作为日期选择器。我试图用javascript检查,但用户输入的日期是过去的。这是我的表单代码:
<input type="text" id="datepicker" name="event_date" class="datepicker">
然后我将如何使用Javascript检查这一点,以确保它不是过去的日期?感谢
答案 0 :(得分:108)
$('#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">
答案 1 :(得分:8)
var datep = $('#datepicker').val();
if(Date.parse(datep)-Date.parse(new Date())<0)
{
// do something
}
答案 2 :(得分:1)
为了让答案更适用于日期选择器更改功能以外的其他内容,您可以创建一个原型来为您处理。
// safety check to see if the prototype name is already defined
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
return this;
}
};
Date.method('inPast', function () {
return this < new Date($.now());// the $.now() requires jQuery
});
// including this prototype as using in example
Date.method('addDays', function (days) {
var date = new Date(this);
date.setDate(date.getDate() + (days));
return date;
});
如果您不喜欢安全检查,可以使用传统方式定义原型:
Date.prototype.inPast = function(){
return this < new Date($.now());// the $.now() requires jQuery
}
使用示例
var dt = new Date($.now());
var yesterday = dt.addDays(-1);
var tomorrow = dt.addDays(1);
console.log('Yesterday: ' + yesterday.inPast());
console.log('Tomorrow: ' + tomorrow.inPast());
答案 3 :(得分:-7)
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;
}
}
}