Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - checking if time is between certain hours of the day

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!

like image 760
fillevoss Avatar asked Jan 29 '13 21:01

fillevoss


2 Answers

Do you increase the day of the year by 1 when you're passing midnight? Otherwise your startHourMilli might be greater than endHourMilli 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.

int start = 21; // let's take your failing example: 21-07
int end = 7;
int hours = (end - start) % 24; // here hours will be 14

Calendar cal = Calendar.getInstance();
// set calendar to TODAY 21:00:00.000
cal.set(Calendar.HOUR_OF_DAY, start);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

long startHourMilli = cal.getTimeInMillis();

// add 14 hours = TOMORROW 07:00:00.000
cal.add(Calendar.HOUR_OF_DAY, hours); 
long endHourMilli = cal.getTimeInMillis();

Let me know if this helps :)

like image 58
ottel142 Avatar answered Sep 21 '22 10:09

ottel142


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.

like image 32
Zadec Avatar answered Sep 19 '22 10:09

Zadec