如何获得2个日期之间的差异? jquery datepicker

时间:2014-02-13 09:17:55

标签: javascript jquery datepicker

我正在尝试使用jquery datepicker计算所选#from day和#to day之间的总天数

"在写这篇文章之前我已经阅读了很多问题所以我只是想问为什么下面的代码不起作用。"

这是代码:

$(function() {

$( "#from" ).datepicker({
numberOfMonths: 1,
minDate:0,
dateFormat: 'dd-mm-yy',
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
$("input[name='to']").val(selectedDate);
var dayFrom = selectedDate; /* Selected From Date */
}
});

$( "#to" ).datepicker({
defaultDate: "+1w",
numberOfMonths: 1,
minDate:0,
dateFormat: 'dd-mm-yy',
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
var dayTo = selectedDate; /* Selected To Date */

$(dayFrom, dayTo).change(function(){
if($(dayFrom).val() && $(dayTo).val()){
var startDate = parseDate($(dayFrom).val());
var endDate = parseDate($(dayTo).val());
var days = calcDaysBetween(startDate, endDate);
var price = calcPrice(days);

$('#finalDagen').html(days);
}
});
function parseDate(s){
var parts = s.split('/');
return new Date(parts[2], parts[0]-1, parts[1]);
}
function calcDaysBetween(startDate, endDate){
return (endDate-startDate)/(1000*60*60*24);
}
}
});
});

2 个答案:

答案 0 :(得分:0)

观察

  • 更改处理程序应注册到from和to元素,而不是注册到包含值
  • 的变量
  • 使用widget方法getDate()来获取小部件的日期值
  • 更改事件应在dom ready处理程序中注册 - 而不是在onClose方法

应该是

jQuery(function ($) {
    var $from = $("#from"),
        $to = $("#to");

    $from.datepicker({
        numberOfMonths: 1,
        minDate: 0,
        dateFormat: 'dd-mm-yy',
        onClose: function (selectedDate) {
            $to.datepicker("option", "minDate", selectedDate);
        }
    });

    $to.datepicker({
        defaultDate: "+1w",
        numberOfMonths: 1,
        minDate: 0,
        dateFormat: 'dd-mm-yy',
        onClose: function (selectedDate) {
            $from.datepicker("option", "maxDate", selectedDate);
        }
    });
    $from.add($to).change(function () {
        var dayFrom = $from.datepicker('getDate');
        var dayTo = $to.datepicker('getDate');
        if (dayFrom && dayTo) {
            var days = calcDaysBetween(dayFrom, dayTo);

            $('#finalDagen').html(days);
        }
    });

    function calcDaysBetween(startDate, endDate) {
        return (endDate - startDate) / (1000 * 60 * 60 * 24);
    }
});

演示:Fiddle

答案 1 :(得分:-1)

尝试减去两个:

var dayDifference = dayTo - dayFrom;