在Javascript中获取两次时间差异

时间:2015-01-07 13:17:55

标签: javascript

我需要计算字符串中给出的时间之间的时差。我有时间在字符串中看到

    var time1 = "07:50";
    var time2 = "08:30";
    var time3 = "24:00";

    for calculating time difference.I tried like this code snippets

    var date1 = new Date(2015, 01,07,  time1.split(":")[0],time1.split(":")[1]);
    var date2 = new Date(2015, 01, 07, time2.split(":")[0], time2.split(":")[1]);
    var date3 = new Date(2015, 01, 07, time3.split(":")[0], time3.split(":")[1]);

    if (date2 > date1) {
        var diff = date2 - date1;
    }

It Working.Hhile我有第三次花时间3并添加如下的条件

    if (date2 > date1) {
        var diff = date2 - date1;
    }else{
        var diff = date3-date2+date1;
    }        

现在差异没有正确显示。我怎么能得到确切的小时和分钟差异。还有其他简单方法。请帮助我

1 个答案:

答案 0 :(得分:0)

您无需创建日期,只需将字符串转换为分钟即可。根据您的原始代码:

var t1 = time1.split(":")[0]*60 + time1.split(":")[1]*1;
var t2 = time2.split(":")[0]*60 + time2.split(":")[1]*1;
var t3 = time3.split(":")[0]*60 + time3.split(":")[1]*1;

现在 diff 将是最小的,您可以转换为hh:mm:

var diff;

if (t2 > t1) {
    diff = t2 - t1;
}else{
    diff = t3 - t2 + t1;
}

function pad(n) {return (n<10? '0':'') + n}
var s = pad(diff/60 | 0) + ':' + pad(diff%60);

console.log(s); // 00:40

你期待什么结果?

您还可以使用一些常规功能:

// Convert H:M:S to seconds
// Seconds are optional (i.e. n:n is treated as h:s)
function hmsToSeconds(s) {
  var b = s.split(':');
  return b[0]*3600 + b[1]*60 + (+b[2] || 0);
}

// Convert seconds to hh:mm:ss
function secondsToHMS(secs) {
  function z(n){return (n<10?'0':'') + n;}
  var sign = secs < 0? '-':'';
  secs = Math.abs(secs);
  return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0) + ':' + z(secs%60);
}

var t1 = hmsToSeconds(time1);
var t2 = hmsToSeconds(time2);
var t3 = hmsToSeconds(time3);

var diff;

if (t2 > t1) {
    diff = secondsToHMS(t2 - t1);
}else{
    diff = secondsToHMS(t3 - t2 + t1);
}

console.log(diff); // 00:40:00