如何用纯JavaScript比较两个时间值?

时间:2017-05-17 10:40:41

标签: javascript datetime time

我尝试比较两个不同的时间来产生差异时间。

>>> import tldextract
>>> ext = tldextract.extract('http://forums.news.cnn.com/')
ExtractResult(subdomain='forums.news', domain='cnn', suffix='com')
>>> ext.domain
'cnn'

收到的值是,

var start_time;
var end_time;

start_time = $('#startTime').val();
end_time = $('#endTime').val();

在这里,如何从这些时间获得 1小时的差异时间?

预期输出: 01:00

这可以用JavaScript吗?

4 个答案:

答案 0 :(得分:1)

希望此代码段有用



function getDifference(t1, t2) {
  //first splitting by white space. FOr example 5:08 PM will be 5:08 and again splitting by :
  var _t1 = (t1.split(" ")[0].split(":")),
    // converting to number to get the time in minute
    toNum1 = Number(_t1[0]) * 60 + Number(_t1[1]),
    _t2 = (t2.split(" ")[0].split(":")),
    toNum2 = Number(_t2[0]) * 60 + Number(_t2[1]),
    // calulating difference
    dif = toNum2 - toNum1;

  var result = ''
  if (dif % 60 === 0) {
    result = dif % 60 + ':00'
  } else if (dif % 60 < 10) {
    result = Math.floor(dif / 60) + ':0' + dif % 60

  } else if (dif % 60 > 10) {
    result = Math.floor(dif / 60) + ':' + dif % 60
  }
  return result


}

console.log(getDifference("5:08 PM", "6:59 PM"))
&#13;
&#13;
&#13;

答案 1 :(得分:1)

过滤到时间字符串部分,解析数字,补偿AM / PM(为什么不只是使用24小时模型?)并返回差异数组。

/**
 * Takes time as "... Hours:Minutes ..." and returns array of integers "[hours, minutes]"
 *
 * @param {string} time
 * @returns
 */
function splitTime(time) {
  return /\d{1,2}:\d{1,2}/ig
    .exec(time)
    .pop()
    .split(":")
    .map(function(a) {
      return parseInt(a, 10);
    });
}

function timeDifference(from, to) {
  var t1 = splitTime(from);
  var t2 = splitTime(to);
  if (from.toLowerCase().indexOf("pm") >= 0) {
    t1[0] = t1[0] + 12;
  }
  if (to.toLowerCase().indexOf("pm") >= 0) {
    t2[0] = t2[0] + 12;
  }
  var diff = [t2[0] - t1[0], t2[1] - t1[1]];
  return diff;
}
console.log("Raw return:", timeDifference("5:08 AM", "6:08 AM"));
console.log("Formatting return:", timeDifference("5:08 AM", "6:08 AM").join(":"));

答案 2 :(得分:0)

&#13;
&#13;
var start_time = "5:08 PM"
var end_time = "6:10 PM"
var d1 = Date.parse('1/1/2000 '+start_time)
var d2 = Date.parse('1/1/2000 '+end_time)
var diff = (d2-d1)/(60*1000)
var h = Math.floor(diff/60)
var m = diff-h*60
var result = h+":"+("00"+m).slice(-2)
document.write(result)
&#13;
&#13;
&#13;

答案 3 :(得分:-1)

你可以使用纯粹的javascript,但时刻会更好。一个未结束的例子就是这样的:

    var date1 = new Date();
    date1.setHours('5:08 PM'.split(':')[0]); //Not checking PM or AM
    date1.setMinutes( ....
    return (Math.abs(date1.getTime()-date2.getTime()) / (1000*60*60)) % 24 //returning only hours you will need to add seconds