Search code examples
androidtimemilliseconds

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!


Solution

  • 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 :)