0

I'm using jquery datetimepicker, I want to get the difference between start time and end time.

How can I calculate it using javascript/jquery code?

I set up the start and end time in html like.

<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>

And, my jquery codes by getting its value:

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

Curently, I'm doing it manually by splitting the Hour and Minutes. Adding validation on it by checking the values before subtracting it.

Is there a best way to do it ?

Please help. Thank you.

aldrien.h
  • 3,437
  • 2
  • 30
  • 52

1 Answers1

0

SOLVED

Thanks to @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);
Community
  • 1
  • 1
aldrien.h
  • 3,437
  • 2
  • 30
  • 52