0

I can't find the solution here in SO so I posted this question. This how I get time difference, but what I am getting is NaN. I've been looking for the cause but with no avail. Any ideas are appreciated.

var totaltime = "";
var check = true;
var timefrom = "1:00";
var timeto = "11:00";
//var timefrom = "10:00";
//var timeto = "19:00";

if (check) {
  //console.log(toSeconds(data[0].timefrom))
  var difference = Math.abs(toSeconds(timefrom) - toSeconds(timeto));
  // format time differnece
  var result = [
    Math.floor(difference / 3600), // an hour has 3600 seconds
    Math.floor((difference % 3600) / 60), // a minute has 60 seconds
    difference % 60
  ];
  // 0 padding and concatation
  console.log(result)
  totaltime = result.map(function(v) {
    return v < 10 ? '0' + v : v;
  }).join(':');
  check = false;
}

console.log(totaltime)

function toSeconds(time_str) {
  //    console.log(time_str)
  // Extract hours, minutes and seconds
  var parts = time_str.split(':');
  // compute  and return total seconds
  return parts[0] * 3600 + // an hour has 3600 seconds
    parts[1] * 60 + // a minute has 60 seconds
    +
    parts[2]; // seconds
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Martin
  • 365
  • 4
  • 7
  • 22
  • 2
    You can't have looked too hard - there's lots of questions about this already: https://www.google.co.uk/search?q=javascript+get+difference+between+two+times&oq=javascript+get+difference+between&aqs=chrome.4.0j69i57j0l4.5646j0j1&sourceid=chrome&ie=UTF-8 – Rory McCrossan Jan 13 '17 at 10:01
  • Do a `console.log` on all the `parts[]` abd their individual results before the return statement in `toSeconds` that should help you :) – Nope Jan 13 '17 at 10:01
  • 1
    Issue is `parts[2]` is `undefined`. Try `(parts[2] || 0)`. Also, there is an extra `+` before `parts[2]` – Rajesh Jan 13 '17 at 10:02
  • What do you get if you log `toSeconds(time From)`? – Mahendran Nadesan Jan 13 '17 at 10:02
  • @MahendranNadesan, i checked it and it return NaN, so toSeconds is wrong, can you show your function toSeconds? and its not duplicate becouse, in this case isn't use momemnt... – Piotr Białek Jan 13 '17 at 10:04
  • 1
    @Rajesh is right though - `parts[2]` is undefined, and really, as long as you only use hh:mm you will not get a 3rd index in `parts`. Try `return (parts[0] * 3600) + (parts[1] * 60);` – Mahendran Nadesan Jan 13 '17 at 10:39

0 Answers0