in my app I'm updating some stuff if the time is between certain hours of the day which the user choose. It works fine if the user chooses something like "07-21", but not with "21-07" which is over the night. How I'm doing to check the time is I'm getting the current hour and converting it into milliseconds. Then I check if the current milli is between the chosen hours (those are also converted into milliseconds). Like this:
if (currentMilli >= startHourMilli && currentMilli <= endHourMilli)
The problem: It doesn't work if the user chooses anything that is over midnight (19-08 for example).
I've tried a lot of stuff but I just can't figure out how to do this.
Any help is appreciated!
I think that ottel142 is almost ok but it shoud be:
I'm answering my own question because I think I came up with something that might work for what I'm trying to do:
It should work even if endMilli is less than startMilli, or have I screwed something up here?
I know I'm a little late to the party, but recently I developed android app that needed to work within given timeframe, and since I didn't like working with
Calendar
I ended up using something like this:Now I know that you found yourself a solution, but I think that my approach may be a little more understandable (at least to newbies that might get confused).
You can always use simple if / else for 24 hour format, without using functions or additional calculations:
For Example1: Full time period from StartHour to StopHour(stop hour include all minutes)
int StartHour = 23; //start from 23:00
int StopHour = 9; // until current hour is 9 that will include until 9:59
int CurrentHour = 2;
At the end if Inside == true CurrentHour is in time range StartHour - StopHour(full stop hour)
And do something else if both equal:
if (StartHour == StopHour) {..............};
For Example2: If you want to stop at this exact StopHour hour, you need some changes:
int StartHour = 23; //start from 23:00
int StopHour = 9; // this will stop after 8:59
int CurrentHour = 2;
At the end if Inside == true CurrentHour is in time range StartHour - StopHour(exact)
Do you increase the day of the year by 1 when you're passing midnight? Otherwise your
startHourMilli
might be greater thanendHourMilli
and your if-clause will always be false.The solution is to use the
add-method
of the Calendar class. Therefore I calculate the interval's length in hours and add this value to our Calendar instance.Let me know if this helps :)
Date has the functions before and after for comparing two dates. Hope this documentation helps you:
http://developer.android.com/reference/java/util/Date.html#after(java.util.Date)
http://developer.android.com/reference/java/util/Date.html#before(java.util.Date)
Best regards.