Javascript时差计算器

时间:2013-06-17 03:07:12

标签: javascript timer

我想知道如何完全作为此演示,还有秒

var start = document.getElementById("start").value;
var end = document.getElementById("end").value;

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);

    return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}

document.getElementById("diff").value = diff(start, end);

DEMO:http://jsfiddle.net/KQQqp/

请帮忙!

非常感谢!

1 个答案:

答案 0 :(得分:1)

尝试

var start = document.getElementById("start").value;
var end = document.getElementById("end").value;

function diff(start, end) {
    start = start.split(":");
    end = end.split(":");
    var startDate = new Date(0, 0, 0, start[0], start[1], start[2] || 0);
    var endDate = new Date(0, 0, 0, end[0], end[1], end[2] || 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);
    diff -= minutes * 1000 * 60;
    var seconds = Math.floor(diff / 1000);

    return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes + ":" + (seconds < 9 ? "0" : "") + seconds;
}

document.getElementById("diff").value = diff(start, end);

演示:Fiddle