使用JavaScript计算时差 [英] Calculate Time Difference with JavaScript

查看:152
本文介绍了使用JavaScript计算时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个HTML输入框,需要计算JavaScript onBlur的时差(因为我需要实时)并将结果插入新的输入框。

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.

格式示例:10:00& 12:30需要给我:02:30

Format example: 10:00 & 12:30 need to give me: 02:30

谢谢!

推荐答案

这是一个可能的解决方案:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆