如何计算Javascript中字符串之间的时差

use*_*055 5 javascript jquery

是我有两个小时的字符串格式,我需要计算javascript的差异,一个例子:

a ="10:22:57"

b ="10:30:00"

差异= 00:07:03?

Fel*_*ing 14

虽然使用Date或库非常好(并且可能更容易),但这里有一个如何通过一点点数学"手动"完成此操作的示例.这个想法如下:

  1. 解析字符串,提取小时,分钟和秒.
  2. 计算总秒数.
  3. 减去这两个数字.
  4. 将秒格式化为hh:mm:ss.

例:

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
           +parts[2];        // seconds
}

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

// compute hours, minutes and seconds
var result = [
    // an hour has 3600 seconds so we have to compute how often 3600 fits
    // into the total number of seconds
    Math.floor(difference / 3600), // HOURS
    // similar for minutes, but we have to "remove" the hours first;
    // this is easy with the modulus operator
    Math.floor((difference % 3600) / 60), // MINUTES
    // the remainder is the number of seconds
    difference % 60 // SECONDS
];

// formatting (0 padding and concatenation)
result = result.map(function(v) {
    return v < 10 ? '0' + v : v;
}).join(':');
Run Code Online (Sandbox Code Playgroud)

DEMO