JqueryUI DatePicker - 计算产生NaN的日期差异

时间:2014-11-20 09:38:14

标签: jquery jquery-ui datepicker nan

我是jquery的新手。所以我对jquery不太了解。我想计算datepicker的天数。我从这里尝试了提示但结果总是NaN。我试过parse,int parse,date parse,结果仍然是NaN。请帮我修复此代码。

I'm using Keith Wood Datepicker基础来自jqueryUI

这是我的代码:

$(function() {
    $('#from,#to').datepick({
    	//dateFormat: 'dd-mm-yyyy',
		minDate: 0,
		maxDate: '+1y',
		changeMonth: true,
		onSelect: (customRange, total),
    });
	
});

function customRange(dates) {
	if (this.id == 'from') {
		$('#to').datepick('option', 'minDate', dates[0] || null);
		$( "#listRender" ).datepick( "option", "minDate", dates[0] || null);
	}
	else {
		$('#from').datepick('option', 'maxDate', dates[0] || null);
		$( "#listRender" ).datepick( "option", "maxDate", dates[0] || null);
	}
}

function total() {
	var start = $('#from').datepick('getDate');
	var end = $('#to').datepick('getDate');
	var total = (end-start) / 1000 / 60 / 60 / 24;
	$('#total_days').val(total);
    //alert(total);
	
}
<p>
  Arrive Date : <input type="text" name="arriveDate" placeholder="Arrival" id="from" readonly="true"/>
</p>

<p>
Departure Date : <input type="text" name="departDate" placeholder="Departure" id="to" readonly="true"/>
</p>

<p>
Total Days : <input type="text" id="total_days" placeholder="Total Day" id="total_days" readonly="true"/>
</p>

2 个答案:

答案 0 :(得分:0)

试试这个:

function total() {
    var start = new Date($('#from').val())||0;
    var end = new Date($('#to').val())||0;

    if(start > 0 && end > 0)
    {
    var total = (end-start) / 1000 / 60 / 60 / 24;
    $('#total_days').val(total);
    //alert(total);
    }
}

<强> DEMO

答案 1 :(得分:0)

仅当两个值都存在时才进行总计算

function total() {
    //looks like getDate is returning an array
    var start = $('#from').datepick('getDate')[0];
    var end = $('#to').datepick('getDate')[0];
    var total = start && end ? (end.getTime() - start.getTime()) / 1000 / 60 / 60 / 24 : '';
    $('#total_days').val(total);
    //alert(total);

}

演示:Fiddle