我怎么知道一个事件花了多少小时

How do I know how many hours it took an event?

本文关键字:多少 小时 事件 一个 我怎么知道      更新时间:2023-09-26

我有这个样本:

链接

代码网页:

<input class="Time1" value="10:00" />
<input class="Time2" value="10:30" />
<input class="Hours" value="0" />
<hr>
<button onclick="calculate()">Calculate</button>

代码 JS:

$(function () {
    function calculate() {
        var hours = parseInt($(".Time2").val().split(':')[0], 10) - parseInt($(".Time1").val().split(':')[0], 10);
        if(hours < 0) hours = 24 + hours;
        $(".Hours").val(hours);
    }
    $(".Time1,.Time2").change(calculate);
    calculate();
});

输入值的时刻为:

1. Time1=10:00;

2. Time2=10:30;

结果将是以下形式

00:30

当前正在计算和结果

is 0

如果相应输入与2:00 p.m. 4:00 p.m.的交换值,则结果将是2的,并且应为02:00

我们如何修复这些错误?你能帮我找到解决方案吗?

提前谢谢你

如果你不想使用像 Moment.js 这样的库(对于像这样的琐碎任务,你不应该这样做),那么最好使用 JavaScript 的原生日期功能:

function recalculate() {
  // Come up with a couple dummy dates with the given times:
  var d1 = new Date("2000-01-01T" + document.getElementById("Time1").value);
  var d2 = new Date("2000-01-01T" + document.getElementById("Time2").value);
  // Calculate their difference in milliseconds
  var msecDifference = (d2 - d1);
  // If it's less than zero, add 24 hours to it (since we're spanning days)
  if (msecDifference < 0) msecDifference += 86400 * 1000; // 86400 seconds in a day
  // And convert the milliseconds back to hours.
  document.getElementById("Output").value = (msecDifference / 1000 / 60 / 60);
}
// Plumbing to make the example interactive.
document.body.addEventListener("change", function(ev) {
  recalculate();
});
recalculate();
From
<input id="Time1" value="10:00">to
<input id="Time2" value="8:30">
<hr>Hours:
<input id="Output" readonly>

只需使用 javascript Date 对象将 2 个输入转换为日期,然后以毫秒为单位计算差异.
从那里,您可以轻松地将毫秒数转换回hh:mm格式的字符串。

请参阅下面的小提琴或代码,注释在代码中解释每个步骤。

小提琴:http://jsfiddle.net/44NCk/194/


.HTML

<input class="Time1" value="10:00" />
<input class="Time2" value="10:30" />
<input class="Hours" value="0" />
<hr>
<button class="calc">Calculate</button>

JavaScript/jQuery

$(document).ready(function() {
   $(".Time1, .Time2").change(calculate);
   $('.calc').click(calculate);
   calculate();
 });
 function calculate() {
   var d1,
     d2,
     t1 = $('.Time1').val().split(/':/g),
     t2 = $('.Time2').val().split(/':/g),
     diff = 0,
     hh = '',
     mm = '';
    d1 = new Date(); // Create date object
    d1.setHours(t1[0]); // Set the hours to match time 1
  d1.setMinutes(t1[1]); // And the minutes
  d2 = new Date(d1.getTime()); // Duplicate the first Date ...
  d2.setHours(t2[0]); // ... and update it's hours to match Time 2 ...
  d2.setMinutes(t2[1]); // ... and it's minutes
  var diff = d2 - d1; // Subtract d1 from d2 to calulcate the difference in ms
  diff += (diff < 0) ? 86400 * 1000 : 0; // d2 is on next day
  // Format difference to hh:mm
  var hh = Math.floor(diff / 1000 / 60 / 60);
  diff -= hh * 1000 * 60 * 60;
  hh = (hh.toString().length === 1) ? '0' + hh : hh; // Add leading '0' if needed
  var mm = Math.floor(diff / 1000 / 60);
  mm = (mm.toString().length === 1) ? '0' + mm : mm; // Add leading '0' if needed
    // Set the difference in the appropriate input
  $('.Hours').val(hh + ':' + mm);
}

我不会为此使用 Date 对象和浮点计算,因为您最终可能会得到1.183333等结果。这是一个仅使用整数并给出确切结果的小"库":

function parse(time) {
    var r = time.toLowerCase().match(/^('d+)(:('d+))?'s*([ap])'.?m/);
    if (r) {
        return {
            h: Number(r[1]) + (r[4] == 'p' ? 12 : 0),
            m: Number(r[3]) || 0
        };
    }
    r = time.split(':');
    return {
        h: Number(r[0]),
        m: Number(r[1]) || 0
    }
}
function delta(t1, t2) {
    var a = parse(t1),
        b = parse(t2);
    return {
        h: b.h - a.h + 24 * (a.h > b.h) - 1 * (a.m > b.m),
        m: b.m - a.m + 60 * (a.m > b.m)
    }
}
function format(p) {
    return [
        p.h < 10 ? '0' : '',
        p.h,
        ':',
        p.m < 10 ? '0' : '',
        p.m
    ].join('');
}
////////
a = '8:30 pm';
b = '03:27';
document.write(format(delta(a, b)));