用 JavaScript 计算时差 [英] Calculate Time Difference with JavaScript
本文介绍了用 JavaScript 计算时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个 HTML 输入框,需要计算 JavaScript onBlur 中的时间差(因为我需要实时)并将结果插入新的输入框.
格式示例:10:00 &12:30需要给我:02:30
谢谢!
解决方案
这是一种可能的解决方案:
function diff(start, end) {start = start.split(":");end = end.split(":");var startDate = new Date(0, 0, 0, start[0], start[1], 0);var endDate = new Date(0, 0, 0, end[0], end[1], 0);var diff = endDate.getTime() - startDate.getTime();var hours = Math.floor(diff/1000/60/60);差异 -= 小时 * 1000 * 60 * 60;var 分钟 = Math.floor(diff/1000/60);//如果使用 24 小时格式的时间选择器,请添加以下行以获取准确的小时数如果(小时<0)小时 = 小时 + 24;return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + 分钟;}
演示: http://jsfiddle.net/KQQqp/>
I have two HTML input boxes, that need to calculate the time difference in JavaScript onBlur (since I need it in real time) and insert the result to new input box.
Format example: 10:00 & 12:30 need to give me: 02:30
Thanks!
解决方案
Here is one possible solution:
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
}
DEMO: http://jsfiddle.net/KQQqp/
这篇关于用 JavaScript 计算时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文