如何计算Javascript中字符串之间的时差 [英] How do I calculate the time difference between strings in Javascript
本文介绍了如何计算Javascript中字符串之间的时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是我有两个小时的字符串格式,我需要计算javascript中的差异,例如:
is that I have two hours in string format and I need to calculate the difference in javascript, an example:
a =10:22:57
a = "10:22:57"
b =10:30:00
b = "10:30:00"
差异= 00:07:03?
difference = 00:07:03 ?
推荐答案
虽然使用日期
或图书馆完全没问题(也可能更容易),这里是一个如何通过一点点数学手动执行此操作的示例。这个想法如下:
Although using Date
or a library is perfectly fine (and probably easier), here is an example of how to do this "manually" with a little bit of math. The idea is the following:
- 解析字符串,提取小时,分钟和秒。
- 计算总秒数。
- 减去两个数字。
- 将秒格式设置为
hh:mm:ss
。
- Parse the string, extract hour, minutes and seconds.
- Compute the total number of seconds.
- Subtract both numbers.
- Format the seconds as
hh:mm:ss
.
示例:
Example:
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(':');
这篇关于如何计算Javascript中字符串之间的时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文