[removed] finding the time difference between two

2019-09-18 07:43发布

I have two <input type="time">. 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 enable computation? Is it possible to avoid involving the use of date in this approach?

In the end, I would like to compute the difference between two time strings and then return the result in minutes. For example, the expected return value of08:00 and 09:00 would be 60 minutes.

3条回答
ゆ 、 Hurt°
2楼-- · 2019-09-18 08:18

Assuming you want to use a 24h clock:

function minutesBetween (a, b) {
  return Math.abs(toMinutes(b) - toMinutes(a))
}

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

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

查看更多
女痞
3楼-- · 2019-09-18 08:27

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.

查看更多
甜甜的少女心
4楼-- · 2019-09-18 08:28

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 
function diff(start, end) {
    const startMinutes = getMinutes(start);
    const endMinutes   = getMinutes(end);
    return endMinutes - startMinutes
}

function getMinutes(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

查看更多
登录 后发表回答