计算输入的日期和时间之间的差异?

时间:2014-05-01 12:18:41

标签: javascript jquery datetime

我有两个输入字段来输入日期,这是一个jquery datepicker。使用它我可以选择日期。他们办理入住手续并查看日期。

同样,我有两个选择框,我可以从中选择时间。他们是登记入住和退房时间。

例如

Check in date: 01/05/2014
Check in time: 13:00


Check out date: 04/05/2014
Check out time: 18:00

我想要的结果:(01/05/2014 13:00)和(04/05/2014 18:00)之间的差异 喜欢 3天5小时

Fiddle

现在我收到结果NAN

以下是我正在使用的脚本:

$(document).ready(function(){
    $("#diff").focus(function(){
        var start = new Date($('#din').val());
        var end = new Date($('#dou').val());
        var diff = new Date(end - start);
        var days = Math.floor(diff/1000/60/60/24);
        var hours = Math.floor((diff % ( 1000 * 60 * 60 * 24)) / 1000 / 60 / 60);
         $("#diff").val(days+' Day(s) '+hours+' Hour(s)');
    });
});

3 个答案:

答案 0 :(得分:1)

Fiddle Demo

$(document).ready(function () {
    function ConvertDateFormat(d, t) {
        var dt = d.val().split('/'); //split date
        return dt[1] + '/' + dt[0] + '/' + dt[2] + ' ' + t.val(); //convert date to mm/dd/yy hh:mm format for date creation.
    }
    $("#diff").focus(function () {
        var start = new Date(ConvertDateFormat($('#din'), $('#tin')));
        var end = new Date(ConvertDateFormat($('#dout'), $('#tout')));
        console.log(start, end);
        var diff = new Date(end - start);
        var days = Math.floor(diff / 1000 / 60 / 60 / 24);
        var hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / 1000 / 60 / 60);
        $("#diff").val(days + ' Day(s) ' + hours + ' Hour(s)');
    });
});

<小时/> ConvertDateFormat(d,t)将日期转换为当前格式。

获取new Date('mm/dd/yy hh:mm')

<小时/> Date
更新

<强>问题

错字

var end = new Date($('#dout').val());
//                         ^ missing t in id it's dout not dou

会导致date无效,因此当您减去NaN时,您会获得invalid Date

Updated Fiddle Demo With your code

答案 1 :(得分:1)

您可以使用datepicker native getDate功能获取日期对象。然后使用this SO answer中有关考虑夏令时的信息,您可以使用UTC日期时间来获得确切的差异。

除了设置日期时间非常简单外,如果您可以更改选项的value,请将它们设置为实际的小时值,类似于:

<select id="tin" name="tin">
    <option value="13">13:00</option>
    <option value="19">19:00</option>
</select>

和这个

<select id="tout" name="tout">
    <option value="12">12:00</option>
    <option value="18">18:00</option>
</select>

这将使代码变得如此简单,仅使用原生日期对象功能来计算您的日期和时间,除非分为24小时以获得从小时开始的日期,类似于:

var _MS_PER_HOUR = 1000 * 60 * 60; // 3600000ms per hour
var outputTextWithSign = '{0}{1} Days(s) {2}{3} Hours(s)'; // included sign
var outputTextWithoutSign = '{0} Days(s) {1} Hours(s)'; // no sign

$(function () {
    $("#din, #dout").datepicker({
        minDate: 0,
        dateFormat: 'dd/mm/yy'
    });
});

$(document).ready(function () {
    $("#diff").focus(function () {
        var startDate = $('#din').datepicker('getDate');
        var endDate = $('#dout').datepicker('getDate');

        // use native set hour to set the hours, assuming val is exact hours
        // otherwise derive exact hour from your values
        startDate.setHours($('#tin').val());
        endDate.setHours($('#tout').val());

        // convert date and time to UTC to take daylight savings into account
        var utc1 = Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(), startDate.getHours(), startDate.getMinutes(), startDate.getSeconds());
        var utc2 = Date.UTC(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(), endDate.getHours(), endDate.getMinutes(), endDate.getSeconds());

        // get utc difference by always deducting less from more
        // that way you always get accurate difference even if in reverse!
        var utcDiff = utc1 > utc2 ? utc1 - utc2 : utc2 - utc1;

        // get total difference in hours
        var msDiff = Math.floor(utcDiff / _MS_PER_HOUR);

        // get days from total hours
        var dayDiff = Math.floor(msDiff / 24);

        // get left over hours after deducting full days
        var hourDiff = Math.floor((msDiff - (24 * dayDiff)));

        //
        // write out results
        //

        // if you really need to show - sign and not just the difference...
        var sign = utc1 > utc2 ? '-' : '';

        // format output text - with (-)sign if required
        var txtWithSign = outputTextWithSign.format(dayDiff ? sign : '', dayDiff, hourDiff ? sign : '', hourDiff);

        // simple format without sign
        var txtNoSign = outputTextWithoutSign.format(dayDiff, hourDiff);

        // assign result - switch with/without sign result as needed
        $("#diff").val(txtWithSign);
        //$("#diff").val(txtNoSign);
    });
});

// Helper for easy string formatting.
String.prototype.format = function () {
    //var s = arguments[0];
    var s  = this;

    for (var i = 0; i < arguments.length; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i]);
    }

    return s;
}

DEMO - 获取日间和小时的差异,将夏令时考虑在内


答案 2 :(得分:0)

使用jQuery datePicker选择日期

和差异尝试这个..

HTML

<input type="text" id="date1">
<input type="text" id="date2">
<input type="text" id="calculated">


$(document).ready(function () {

var select=function(dateStr) {
      var d1 = $('#date1').datepicker('getDate');
      var d2 = $('#date2').datepicker('getDate');
      var diff = 0;
      if (d1 && d2) {
            diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
      }
      $('#calculated').val(diff);
}

$("#date1").datepicker({ 
    minDate: new Date(2012, 7 - 1, 8), 
    maxDate: new Date(2012, 7 - 1, 28),
    onSelect: select
});
$('#date2').datepicker({onSelect: select});
});