I have a train schedule app, and I am trying to calculate the difference between two times with the following format HH:MM, so my users can easily see if the train is late (note: I am fetching the “real” data from the internet, so it is up-to-date). This is what I am doing at the moment:
//schedule time of the train
int hs=12;
int ms=0;
//real time of the train
int hr=12;
int mr=15;
int t1=hs*60 + ms;
int t2=hr*60 + mr;
int d; //integer for the difference in minutes
if(hr>=hs) d=t2-t1; //standard situation
else d=1440+t2-t1; //for situation like sch: 23:55, real: 00:05
Is this correct? Am I forgetting anything? I had a few tries before this algorithm, all of them had minor bugs, which could confuse my users. As far as I see, this one does not have any glitch, at least I couldn’t find any.
P.S.: I won’t use any 3rd party libs, so I have to write my own algorithm, tho I hope it will be the final…
Thx!
EDIT: note: the values of hs/ms/hr/mr are hardcoded in this example, tho in my app, I have them updated correctly, for each row.
This should give you the minute difference on any day, or over the border of any day, except for daylight savings time.