0

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"
}
Rob
  • 14,746
  • 28
  • 47
  • 65
Filth
  • 3,116
  • 14
  • 51
  • 79

2 Answers2

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));
Gavin
  • 4,365
  • 1
  • 18
  • 27
  • Exactly what I was after - thanks @Gavin. Can you please explain the thought process on this? It seems I definitely had to convert the strings into integers and do comparisons that way? – Filth Nov 21 '16 at 18:49
  • 1
    `.split(':')` will give you an array with the first index being the hour and the second being the minutes. You then just have to subtract the values. If the minutes are negative, we know it's not a full hour, so subtract an hour and add 60 minutes to get us to the right spot. – Gavin Nov 21 '16 at 18:54
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)
kjonsson
  • 2,799
  • 2
  • 14
  • 23
  • If the format of a date is not ISO 8601, `Date.parse` can yield different values for the same string... – Heretic Monkey Nov 21 '16 at 18:30
  • @MikeMcCaughan yeah I was just presuming that he always had a "hour:minute" string. Would need more information to do a broader/better answer. – kjonsson Nov 21 '16 at 18:31