Reputation: 1058
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.
Upvotes: 1
Views: 1533
Reputation: 643
You should use the Java Date and Calendar and DateFormat utility classes to achieve what you want (they are not 3rd party, they are java libraries and included into the Android SDK).
You have a great exemple for what you want here: Is there a function to calculate the difference between two times and display a relative result?
For the DateFormat class you have a good example here: http://www.exampledepot.com/egs/java.text/formatdate.html
Upvotes: 1
Reputation: 1591
This should give you the minute difference on any day, or over the border of any day, except for daylight savings time.
Upvotes: 1