7

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

a = "10:22:57"

b = "10:30:00"

差异 = 00:07:03 ?

4

4 回答 4

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(':');

演示

于 2013-06-17T22:02:30.677 回答
4

用它们制作两个Date物体。然后就可以比较了。

从您希望比较的两个日期中获取值,然后进行减法。像这样(假设foobar是日期):

var totalMilliseconds = foo - bar;

这将为您提供两者之间的毫秒数。一些数学会将其转换为天、小时、分钟、秒或您希望使用的任何单位。例如:

var seconds = totalMilliseconds / 1000;
var hours = totalMilliseconds / (1000 * 3600);

至于Date从 a获取 a string,您必须查看构造函数(检查第一个链接),并以最适合您的方式使用它。快乐编码!

于 2013-06-17T21:42:03.500 回答
3

如果您的时间总是少于 12 小时,这是一个非常简单的方法:

a = "10:22:57";
b = "10:30:00";
p = "1/1/1970 ";

difference = new Date(new Date(p+b) - new Date(p+a)).toUTCString().split(" ")[4];
alert( difference ); // shows: 00:07:03

如果您需要格式化超过 12 小时,则渲染会更复杂,日期之间的 MS # 使用此数学是正确的...

于 2013-06-17T21:48:48.207 回答
0

你必须使用日期对象: http ://www.w3schools.com/jsref/jsref_obj_date.asp

然后比较: 如何在javascript中计算日期差异

于 2013-06-17T21:44:28.050 回答