This pseudo-code gives you the algorithm to work out the difference in minutes.
It assumes that, if the start time is after the end time, the start time was actually on the previous day.
startx = starthour * 60 + startminute
endx = endhour * 60 + endminute
duration = endx - startx
if duration < 0:
duration = duration + 1440
The startx
and endx
values are the number of minutes since midnight.
This is basically doing:
- Get number of minutes from start of day for start time.
- Get number of minutes from start of day for end time.
- Subtract the former from the latter.
- If result is negative, add number of minutes in a day.
Don't be so sure though that you can't use date/time manipulation functions. You may find that you could easily construct a date/time and calculate differences with something like:
DateTime startx = new DateTime (1,1,2010,starthour,startminute,0);
DateTime endx = new DateTime (1,1,2010,endhour ,endminute ,0);
Integer duration = DateTime.DiffSecs (endx,startx) / 60;
if (duration < 0)
duration = duration + 1440;
although it's probably not needed for your simple scenario. I'd stick with the pseudo-code I gave above unless you find yourself doing some trickier date/time manipulation.
If you then want to turn the duration (in minutes) into hours and minutes:
durHours = int(duration / 60)
durMinutes = duration % 60 // could also use duration - (durHours * 60)