我怎样才能找到两次之间的差异

时间:2018-05-27 14:21:45

标签: javascript jquery time

如何在JavaScript中找到时间差异?

这是我提出的伪代码

var firstTime = "20:24:00";
var secondTime = "20:00:52";
console.log(firstTime - secondTime);// 23:08 (23 minutes, 8 seconds)

3 个答案:

答案 0 :(得分:1)

你可以使用new Date().setHours()来制作日期,然后减去它们,从差异中创建一个新日期:

var firstTime = "20:24:00";
var secondTime = "20:00:52";

//                                 transform variables into parameters
let dateA = new Date().setHours(...(firstTime.split(":")));
let dateB = new Date().setHours(...(secondTime.split(":")));

let diff = new Date(dateA-dateB);

console.log(`Differnce: ${diff.getUTCHours()}:${diff.getUTCMinutes()}:${diff.getUTCSeconds()}`);

答案 1 :(得分:0)

试试这个:

var myDate1 = new Date();   
myDate1.setHours(20, 24, 00, 0);
var myDate2 = new Date();
myDate2.setHours(20, 00, 52, 0);

如果直接减去它们,它会给你一个时间戳值。您可以通过说:

来转换此值
var result = myDate1 - myDate2; // returns timestamp
var hours = new Date(result).getHours(); // returns hours

答案 2 :(得分:0)

前段时间我做了一个类似于描述的功能:

let timeOp = function(operation, initial, value) {
  // define the type of operation in bool if needed
  if(typeof operation == "string") {
    var operation = (operation == 'add') ? true : false;
  }

  // convert to minutes `value` if needded
  if(!Number.isInteger(value)) {
    var time = value.split(':');
    value = parseInt(time[0]) * 60 + parseInt(time[1]);
  }

  // split the string and get the time in minutes
  var time = initial.split(':');
  time = parseInt(time[0]) * 60 + parseInt(time[1]);

  // add or substract `value` to minute
  time += (operation) ? value : -value;

  // standardise minutes into hours
  var hour = Math.floor(time / 60);
  var minute = time % 60;

  // return with '0' before if needed
  return hour + ':' + ((minute>=10) ? minute : ('0' + minute))
}

let firstTime = "20:24";
let secondTime = "20:00";
console.log(timeOp('substract', firstTime, secondTime)

它不完美,不允许使用秒。但是你可以通过修改上面的代码很容易地解决这个问题。