我正在尝试计算结束日期的模糊方法的天数。但是我收到了'NAN'。什么可能是错的?我收到了'NAN'。
$('#EndDate').blur(function () {
var diff = dateDiff($('#StartDate').val(), $('#EndDate').val());
alert(diff);
});
function dateDiff(startDate, endDate) {
return endDate.getDate() - startDate.getDate();
}
答案 0 :(得分:2)
.getDate()
没有为字符串对象定义(这是.val()
给你的),所以你会得到2 undefined
个变量试图相互减去它们,并且undefined - undefined === 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!";
}
另外,我会使用提供的blur
事件代替onSelect
,而不是:
$('#EndDate').datepicker({
onSelect: function() {
var diff = dateDiff($('#StartDate').datepicker("getDate"),
$('#EndDate').datepicker("getDate"));
alert(diff);
}
});
答案 1 :(得分:0)
这对我有用
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);
}