Javascript JQuery中的日期差异
我试图用模糊方法计算结束日期的天数。但我收到了“NAN”这个词,怎么可能是错的呢?我收到了“楠”Javascript JQuery中的日期差异,javascript,jquery,jquery-ui,Javascript,Jquery,Jquery Ui,我试图用模糊方法计算结束日期的天数。但我收到了“NAN”这个词,怎么可能是错的呢?我收到了“楠” $('#EndDate').blur(function () { var diff = dateDiff($('#StartDate').val(), $('#EndDate').val()); alert(diff); }); function dateDiff(startDate, endDate) { return endDate.getDate() - start
$('#EndDate').blur(function () {
var diff = dateDiff($('#StartDate').val(), $('#EndDate').val());
alert(diff);
});
function dateDiff(startDate, endDate) {
return endDate.getDate() - startDate.getDate();
}
不是为字符串对象定义的(这就是给您的),因此您将得到2个未定义的
变量,它们试图彼此相减,并且未定义-未定义===NaN
相反,您需要从两个日期选择器中获取日期,并按如下方式减去它们:
$('#EndDate').blur(function () {
var diff = dateDiff($('#StartDate').datepicker("getDate"),
$('#EndDate').datepicker("getDate"));
alert(diff);
});
function dateDiff(startDate, endDate) {
if(endDate && startDate) //make sure we don't call .getTime() on a null
return (endDate.getTime() - startDate.getTime()) / (1000*60*60*24);
return "You must complete both dates!";
}
$('#EndDate').datepicker({
onSelect: function() {
var diff = dateDiff($('#StartDate').datepicker("getDate"),
$('#EndDate').datepicker("getDate"));
alert(diff);
}
});
另外,我将使用提供的
onSelect
事件,而不是blur
,如下所示:
$('#EndDate').blur(function () {
var diff = dateDiff($('#StartDate').datepicker("getDate"),
$('#EndDate').datepicker("getDate"));
alert(diff);
});
function dateDiff(startDate, endDate) {
if(endDate && startDate) //make sure we don't call .getTime() on a null
return (endDate.getTime() - startDate.getTime()) / (1000*60*60*24);
return "You must complete both dates!";
}
$('#EndDate').datepicker({
onSelect: function() {
var diff = dateDiff($('#StartDate').datepicker("getDate"),
$('#EndDate').datepicker("getDate"));
alert(diff);
}
});
.这对我很有效
function calculate(start_date,end_date)
{
var t1= start_date ;
var t2= end_date;
// The number of milliseconds in one day
var one_day=1000*60*60*24;
//Here we need to split the inputed dates to convert them into standard format
var x=t1.split(“/”);
var y=t2.split(“/”);
//date format(Fullyear,month,date)
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0]);
//Calculate difference between the two dates, and convert to days
numberofDays=Math.ceil((date2.getTime()-date1.getTime())/(one_day));
// numberofDays gives the diffrence between the two dates.
$(‘#Input_type_text).val(numberofDays);
}
我在endDate.getTime()@nav100收到“对象不支持”错误消息-您没有使用jQuery UI日期选择器吗?如果没有…你在用什么,我被你的问题标签弄糊涂了…@nav100-啊,我正在按原样修改你的代码,你需要在那里进行额外的检查,比如
if(endDate&&startDate)
在dateDiff
函数中进行检查,以确保你没有对null调用.getTime()
。很抱歉造成混淆。我正在使用UI日期选择器。我收到的“结束日期为空”错误消息。@nav100-我更新了上面的代码,以显示空检查应该是什么样子,以及底部的演示。