Bootstrap(Twitter)Datepicker差异计算返回“NaN”

时间:2013-07-05 14:44:17

标签: javascript jquery twitter-bootstrap datepicker

以下代码在更改日期返回“NaN”(非数字)值。流量是正确的我想但我无法弄清楚它是如何返回NaN的。

$(function() {    
$('.datepicker').datepicker({format: "yyyy-mm-dd"});

    var calculateDuration = function() {
    var start_date = $('#start_date').datepicker('getDate');
    var end_date = $('#end_date').datepicker('getDate');
    document.getElementById('reservation_duration').value = (Number(end_date) - Number(start_date)) / 86400000;
    }

$('#end_date').change(calculateDuration);
$('#start_date').change(calculateDuration);

});

这是日期选择器:http://www.eyecon.ro/bootstrap-datepicker/

2 个答案:

答案 0 :(得分:4)

.datepicker('getDate')不是有效的方法。您可能只想要字段的值,例如$('#start_date').val()

<强>更新 您仍然需要将字段值转换为适合算术的格式:

var startDate = new Date($('#start_date').val());
var endDate = new Date($('#end_date').val());
var delta = endDate - startDate;

答案 1 :(得分:1)

跟随AndréDion的建议,并使其成功!

$(function() {    
    $('.datepicker').datepicker({format: "yyyy-mm-dd"});

var calculateDuration = function() {
    var startDate = new Date($('#start_date').val());
    var endDate = new Date($('#end_date').val());
    var diff = endDate - startDate;
    document.getElementById('reservation_duration').value = (Number(diff) / 86400000) +1;
}

$('#end_date').change(calculateDuration);
$('#start_date').change(calculateDuration);

});