I’m trying to solve a task that I have to do that is to calculate the amount of seconds between a star time and a end time like a race. In the format hhmmss. With the amount of seconds finally calculate the result in hours minutes and seconds. This is a beginners course with non-objective programming, so the code I use must be simple and without any extra classes to handle time. The reason why I ask is because my calculation sometimes calculate a wrong result. I have done it like this:
totalAmountOfSecondsPerHour = (endHour - startHour) * 3600;
totalAmountOfMinutesPerMinutes = Math.abs((endMinutes - startMinutes) * 60);
totalAmountOfSeconds = Math.abs(endSeconds - startSeconds));
I use Math.abs to get rid of negative numbers.
To get the total amount in seconds I add all variables. Finally to get the result time in hhmmss I do like this:
resultHour = totalAmountOfSeconds / 3600;
rest totalAmountOfSeconds % 3600;
resultMinutes = rest / 60;
resultSeconds = rest % 60;
When I enter a starting time like 150030 and end time like 165015 the result is 1 hour 50 minutes an 15 seconds. I guess i should be more correct if it was 45 seconds!? What could be wrong in my calculation? Is there a better way or could I modify or simplify my code the make a correct result? Preciate some help! Thanks!
It’s because you use the Math.abs()
let give you a small example: The app start at 00:00:59 and finish 2 seconds later so at 00:01:01
so 60 + 58 = 118 seconds instead of 2. If we remove the Math.abs, we’ll have:
60 + (-58) = 2 seconds (like it’s suppose).