0

I have 2 strings "18:13:10" and "15:45:11" , I need to compute the number of hours between them ? For example a result of 6 hours and 17 minutes.

I'am working with reactjs.

Thanks

xgeek652
  • 305
  • 3
  • 17
  • Duplicate of [Converting a time string to a time value in javascript](https://stackoverflow.com/q/46591254/215552) and [How to get the hours difference between two date objects?](https://stackoverflow.com/q/19225414/215552) – Heretic Monkey Mar 20 '20 at 16:10
  • How is there "6 hours and 17 minutes" between 18:13:10 and 15:45:11? – Heretic Monkey Mar 20 '20 at 16:32
  • Does this answer your question? [Javascript return number of days,hours,minutes,seconds between two dates](https://stackoverflow.com/questions/13903897/javascript-return-number-of-days-hours-minutes-seconds-between-two-dates) – Heretic Monkey Mar 20 '20 at 16:34

2 Answers2

1

Let Date() do the heavy lifting for you:

    const d1 = new Date('1970-01-01T' + "18:13:10" + 'Z');
    const d2 = new Date('1970-01-01T' + '15:45:11' + 'Z');
    const diff = d1 - d2; // 887900 

The time difference is in milliseconds. To get hours and minutes and seconds:

    const hours = Math.floor(diff/(1000*60*60)); // 2
    const mins = Math.floor((diff-(hours*1000*60*60)) / (1000*60)); // 27
    const secs = Math.floor(
      (diff-(hours*1000*60*60)-(mins*1000*60)) / 1000); // 59
terrymorse
  • 6,771
  • 1
  • 21
  • 27
0

Just create two instances of Date object prepending a date to the full time string. Use getTime and calculate the time difference. Then use getHours getMinutes and getSeconds methods on Date difference.

 const d1 = new Date('1970-01-01 ' + "18:13:10");
 const d2 = new Date('1970-01-01 ' + '10:01:01');

 var difference = d1.getTime() - d2.getTime();

 console.log(new Date(difference).getHours()-1 + ' ' + new Date(difference).getMinutes()+ ' ' + new Date(difference).getSeconds())
koalaok
  • 5,075
  • 11
  • 47
  • 91