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

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

a =“10:22:57”

b =“10:30:00”

差异= 00:07:03?

尽管使用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(':'); 

DEMO

从中生成两个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中的日期差异