Date difference in JQuery received NAN
I am trying to calculate the days on Blur method of End Date. But I received 'NAN'.What at could be wrong? I received 'N开发者_开发技巧AN'.
$('#EndDate').blur(function () {
var diff = dateDiff($('#StartDate').val(), $('#EndDate').val());
alert(diff);
});
function dateDiff(startDate, endDate) {
return endDate.getDate() - startDate.getDate();
}
.getDate()
isn't defined for string objects (which is what .val()
gives you), so you'll get 2 undefined
variables trying to subtract one another battling it out, and undefined - undefined === NaN
.
Instead, you need to get the date from both date pickers and subtract them like this:
$('#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!";
}
Also, instead of blur
, I'd use the onSelect
event provided, like this:
$('#EndDate').datepicker({
onSelect: function() {
var diff = dateDiff($('#StartDate').datepicker("getDate"),
$('#EndDate').datepicker("getDate"));
alert(diff);
}
});
You can test it out here.
This worked for me
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);
}
精彩评论