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

3

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

7 Comments

I tried to change 887900 ms to hours using this : timecalculator.net/milliseconds-to-hours and the result is 0.24 hours
You need to have the next day in d2.
@xgeek95 const hours = Math.floor(ms/(1000*60*60)) and const minutes = Math.floor(ms/(1000*60))
@HereticMonkey Why use a different day for d2? The question does not specifiy a different day.
Well, the expected outcome, "6 hours and 17 minutes" does not appear to square with the difference between 15:45 and 18:13 if they are on the same day (that would be 2 hours and 27 minutes). But it doesn't square going the other way either, so who knows?
|
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())

2 Comments

Questions which explain code are downvoted less often that just a dump of code, especially when that code uses different values than the OP.
Oh really? Just edit my answer btw. Added some explanation to my dump of code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.