Filth Filth - 14 days ago 9
Javascript Question

Calculate time difference | strings

I want to display the amount of minutes between the scheduled time and expected time.

This is not to compare, this is to calculate how many minutes there are in different times in both scheduled and expected.

Since both times are displayed as a string, do I need to convert string to a number and then do a comparison?

All I want to return is the difference in time as a number.

Here is my object:

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

Answer

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

function getTimeDifference(scheduled, expected) {
  scheduled = scheduled.split(':');
  expected = expected.split(':');
  var hours = expected[0] - scheduled[0];
  var minutes = expected[1] - scheduled[1];
  if (minutes < 0) {
    hours--;
    minutes += 60;
  }
  if (hours)
    return hours + ':' + minutes;
  return 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));

Comments