Skip to content Skip to sidebar Skip to footer

Javascript: Finding The Time Difference Between Two 'time' Strings Without Involving Date

I have two . By default, each input collects a time value as a string. For example, '08:30'. How can I convert this string into an object which would then

Solution 1:

Just do it as if you only had pen and paper:

  • 12:45 => 12 × 60 + 45 = 765 minutes
  • 08:30 => 8 × 60 + 30 = 510 minutes
  • 765 - 510 = 255
  • Integer division: 255 / 60 = 4 hours
  • Remainer: 255 - 60 × 4 = 15 minutes
  • Result: 04:15

You can parse from string using regular expressions:

var parts = "08:45".match(/^(\d+):(\d+)$/);
console.log(+parts[1], +parts[2], +parts[1] * 60 + +parts[2]);

... and formatting back to string should not be very difficult either.

Solution 2:

Assuming you want to use a 24h clock:

functionminutesBetween (a, b) {
  returnMath.abs(toMinutes(b) - toMinutes(a))
}

functiontoMinutes (time) {
  time = /^(\d{1,2}):(\d{2})$/.exec(time)
  return time[1]*60 + +time[2]
}

console.log(minutesBetween('8:30', '9:30')) //=> 60

Solution 3:

Generally speaking I whould suggest using Date insted of using custom functions, but just for your case this is the example function:

const timeStart = "8:00:00";
const timeEnd   = "8:10:00";
//Handles only time with format in hh:mm or hh:mm:ss//For more complicated cases use Date functiondiff(start, end) {
    const startMinutes = getMinutes(start);
    const endMinutes   = getMinutes(end);
    return endMinutes - startMinutes
}

functiongetMinutes(strTime) {
    const time = strTime.split(':');
    return (time[0] * 60 + time[1]*1);
}

alert(diff(timeStart, timeEnd));

Note that this function is not responsible for validation of the time difference only the computation. You should validate you input

Post a Comment for "Javascript: Finding The Time Difference Between Two 'time' Strings Without Involving Date"