I have a problem with some code I have been producing in JavaScript. I want to calculate the difference between two times on a 24 hour clock. The data comes from two input time fields:
<input type="time" id="start" />
<input type="time" id="end" />
Because of this the times come in a string 00:00, which doesn't help for number calculations.
The way I worked it out was to minus the start from the end. This works perfectly if the the end time is greater, however if the end time is past 11:00 (00:00), I end up with a negative number. I have tried adding 24 to the result if the end is lower than the start but I still get a negative number. This may seem like a dumb question but I was never that good at maths.
var numHours;
if(time_end < time_start){
numHours = parseInt(t_e.substring(0,2)) - parseInt(t_s.substring(0,2)) + 24;
}else{
numHours = parseInt(t_e.substring(0,2)) - parseInt(t_s.substring(0,2));
}
There is probably (definitely) a better way of doing this but how can I get this to work. Also could I calculate the minutes as well to get more accurate time difference.
I'm a beginner, and some whiz is probably going to come up with an answer in like 2 lines :), but here it is.....this works. input is a string in the form of "1:20pm-2:30am".
The solutions provided aren't accounting for the day boundary effectively. And all of this assumes the difference is less than 24 hours. Meaning that we have an upper boundary on the difference between start and end of 23 hours and 59 minutes, otherwise we are confused by the result. But remember that as described a real use case is that an event starts at 11pm and ends at 1am (from 23:00 to 1:00) and the difference is 2 hours NOT 22 hours.
And I didn't check, but I believe you could just do this, but I'm not checking it :
A simple solution that might work best for this limited use-case is to convert both times into total minutes since the start of the day, and then subtract.
Pseudocode:
It's up to you how you want to handle a negative result. Maybe give the user an error message, and tell them that the start time has to come before the end time?