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

How do I calculate the time difference between strings in Javascript

本文关键字:之间 字符串 时差 Javascript 何计算 计算      更新时间:2023-09-26

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

a = "10:22:57"

b = "10:30:00"

虽然使用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(':');

制作两个Date对象。然后你可以比较。

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

var totalMilliseconds = foo - bar;

将给出两者之间的毫秒数。一些数学运算会把它转换成天、小时、分钟、秒或任何你想用的单位。例如:

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

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

如果你的时间总是少于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值是正确的使用这个数学…

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

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