使用datepicker获取两个日期之间的天数

时间:2013-04-11 13:57:59

标签: javascript jquery jquery-ui date datepicker

$(function () {
    $("#from").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 3,
        onClose: function (selectedDate) {
            $("#to").datepicker("option", "minDate", selectedDate);
        }
    });
    $("#to").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 3,
        onClose: function (selectedDate) {
            $("#from").datepicker("option", "maxDate", selectedDate);
        }
    });
});

$("#to").change(function () {
    var final = $("#to").datepicker("getDate");
    var start = $("#from").datepicker("getDate");
    var days = new Date(final - start);
    alert(days);
});

<label for="from">From</label>
<input type="text" id="from" name="from" />
<label for="to">to</label>
<input type="text" id="to" name="to" />

这是我到目前为止所做的,我假装每次填写最后日期时都会获得2个日期之间的天数。我因转换而遇到麻烦:s

Fiddle

2 个答案:

答案 0 :(得分:4)

我相信最重要的是datepicker('getDate')已经返回一个Date对象,因此finalstart已经是日期对象。

现在您有两个日期对象,您可以在以下线程中对代码进行采样以获取它们之间的天数

How to calculate the number of days between two dates using JavaScript?

以下代码直接从主题和谷歌中删除:您可以正确填写

var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);

var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));

答案 1 :(得分:0)

以下示例对我来说很好。

$(document).ready(function(){
   var $datepicker1 =  $( "#firstday" );
   var $datepicker2 =  $( "#lastday" );
   $datepicker1.datepicker();
   $datepicker2.datepicker({
       onClose: function() {
           var fromDate = $datepicker1.datepicker('getDate');
           var toDate = $datepicker2.datepicker('getDate');
           // date difference in millisec
           var diff = new Date(toDate - fromDate);
           // date difference in days
           var days = diff/1000/60/60/24;

           alert(days);
       }
   });
});

参考: - calculate number of days between two dates in jquery datepicker