如何在jquery datetimepicker中计算2次之间的差异?

时间:2016-06-02 03:01:26

标签: javascript datetimepicker bootstrap-datetimepicker

我使用jquery datetimepicker,我希望得到开始时间和结束时间之间的差异。

如何使用javascript / jquery代码计算它?

我在html中设置了开始和结束时间,如

<div class='input-group date' id='time_starts_at'>
  <input class="form-control" placeholder="Time Start's At *" autocomplete="off" type="text" name="" id="calendar_starts_at_time">
  <span class="input-group-addon">
    <span class="glyphicon glyphicon-time"></span>
  </span>
</div>

<div class='input-group date' id='time_ends_at'>
  <input class="form-control" placeholder="Time End's At *" autocomplete="off" type="text" name="" id="calendar_ends_at_time">
  <span class="input-group-addon">
      <span class="glyphicon glyphicon-time"></span>
  </span>
</div>

并且,我的jquery通过获取其值来编码:

var timeFrom = $start_time.data('date');
var timeTo = $end_time.data('date');

Curently ,我是通过分割小时和分钟来手动完成的。通过在减去之前检查值来添加验证。

有最好的方法吗?

请帮忙。谢谢。

1 个答案:

答案 0 :(得分:0)

<强>解决

感谢@Felix Kling,How do I calculate the time difference between strings in Javascript

function toSeconds(time_str) {
    // Extract hours, minutes and seconds
    var parts = time_str.split(':');
    // compute  and return total seconds
    return parts[0] * 3600 + // an hour has 3600 seconds
    parts[1] * 60; // a minute has 60 seconds
}

var a = "10:55" //start time
var b = "12:00" // end time

var difference = Math.abs(toSeconds(a) - toSeconds(b));

// format time difference
var result = [
    Math.floor(difference / 3600), // an hour has 3600 seconds
    Math.floor((difference % 3600) / 60), // a minute has 60 seconds
    difference % 60
];
// 0 padding and concatation
result = result.map(function(v) {
    return v < 10 ? '0' + v : v;
}).join(':');
alert(result);