计算时差|字符串

时间:2016-11-21 18:19:30

标签: javascript

我想显示预定时间和预期时间之间的分钟数。

这不是比较,而是计算在计划和预期的不同时间内有多少分钟。

由于两个时间都显示为字符串,我是否需要将字符串转换为数字然后进行比较?

我想要返回的只是数字时间的差异。

这是我的目标:

{
station: "Macclesfield",
scheduled: "15:41",
expected: "15:50",
platform: "1"
}

2 个答案:

答案 0 :(得分:1)

var data = {
  station: "Macclesfield",
  scheduled: "15:41",
  expected: "15:50",
  platform: "1"
}

function getTimeDifference(scheduled, expected) {
  scheduled = scheduled.split(':'); //get array [hours, minutes]
  expected = expected.split(':');
  var hours = expected[0] - scheduled[0]; //difference in hours
  var minutes = expected[1] - scheduled[1]; //difference in minutes
  if (minutes < 0) { //if minutes are negative we know it wasn't a full hour so..
    hours--; //subtract an hour
    minutes += 60; //add 60 minutes
  } //now we're ok
  if (hours) //if hours has a value
    return hours + ':' + minutes;
  return minutes; //hours is 0 so we only need the minutes
}

console.log(getTimeDifference(data.scheduled, data.expected));

data.expected = "16:00";

console.log(getTimeDifference(data.scheduled, data.expected));

data.expected = "17:00";

console.log(getTimeDifference(data.scheduled, data.expected));

答案 1 :(得分:0)

var obj = { scheduled: "15:41", expected: "15:50" }
var milliSeconds = Date.parse(`01/01/2011 ${obj.expected}:00`) - Date.parse(`01/01/2011 ${obj.scheduled}:00`)
var minutes = milliSeconds / (1000 * 60)
var hours = milliSeconds / (1000 * 60 * 60)