计算javascript中的时差

时间:2014-06-17 11:37:31

标签: javascript datetime

我想在两个给定时间和一个日期编号之间创建一个时间差异计算器。 另外我想告诉你我已经输入了4个字段:time1,time2,days和timediff。

我想要的时间格式非常简单,例如:7:00为700,9:32为932,16:50为1650等等......

现在我还有日输入字段,我可以输入一些数字,例如:1(第一天,第二天2,依此类推)。

我希望如果我把1(第一天)不计算天数,只计算timediff,因为它是同一天。但是如果我在日期字段上加2,那么24小时(一天)加入timediff,如果我把3 48小时(两天)加入等等......

我有类似的东西,但是效果不好,当我改变那天结果搞砸了......

var time1 = document.getElementById('indulas').value;
var time2 = document.getElementById('erkezes').value;
var day = document.getElementById('nap').value;
if (day > "1"){ day * 2400 };
var time = (time2 * day) - time1;
document.getElementById('ido').value = time;

1 个答案:

答案 0 :(得分:1)

这不能解决为HHMM格式减去两次因为小时只有60分钟(例如900 - 732 = 168不等于正确的1小时28分钟)

此脚本应该可以使用

function pad(num, size) { // num = number which gets the leading zeros; size = number of digits the string will have (in your case 2)
    var s = num.toString(); // convert integer to string
    while (s.length < size) s = "0" + s; // if number of digits is smaller than requested, add leading zeros
    return s; // return the number (as string) with leading zeros
}

var time1 = document.getElementById('indulas').value.match(/.{2}/g),
    // split string each 2 characters ("0932" -> ["09", "32"])
    time2 = document.getElementById('erkezes').value.match(/.{2}/g),
    // day 1 is today, day 2 - 1 adds 24 hours
    days = parseInt(document.getElementById('nap').value)-1,

    // start date on day 0 at HH, MM
    startDate = new Date(0, 0, 0, parseInt(time1[0]), parseInt(time1[1])),
    // end date on day 0 + days at HH, MM
    endDate = new Date(0, 0, days, parseInt(time2[0]), parseInt(time2[1])),
    // subtract dates in milliseconds
    diff = endDate.getTime() - startDate.getTime(),

    // hour and minute in miliseconds
    hour_in_mili= 1000 * 60 * 60,
    minute_in_mili = 1000 * 60,

    // calculate number of hours in diff time
    hours = Math.floor(diff / hour_in_mili),
    // calculate number of minutes in the diff time what left after subtracting the hours
    minutes = Math.floor((diff - (hours * hour_in_mili)) / minute_in_mili);

    /*
       if indulas.value = "0932", erkezes.value = "1650", nap.value = "1"
       script shows "7:18"
    */

document.getElementById('ido').value = hours + ":" + pad(minutes, 2);