Check if time is inbetween timerange in Android

android, java, range, time

Solution

Initialize variables and change the return type of your method to boolean.

private Calendar fromTime;
private Calendar toTime;
private Calendar currentTime;

public boolean checkTime(String time) {
try {
    String[] times = time.split("-");
    String[] from = times[0].split(":");
    String[] until = times[1].split(":");

    fromTime = Calendar.getInstance();
    fromTime.set(Calendar.HOUR_OF_DAY, Integer.valueOf(from[0]));
    fromTime.set(Calendar.MINUTE, Integer.valueOf(from[1]));

    toTime = Calendar.getInstance();
    toTime.set(Calendar.HOUR_OF_DAY, Integer.valueOf(until[0]));
    toTime.set(Calendar.MINUTE, Integer.valueOf(until[1]));

    currentTime = Calendar.getInstance();
    currentTime.set(Calendar.HOUR_OF_DAY, Calendar.HOUR_OF_DAY);
    currentTime.set(Calendar.MINUTE, Calendar.MINUTE);
    if(currentTime.after(fromTime) && currentTime.before(toTime)){
        return true;
    }
    } catch (Exception e) {
        return false;
    }
    return false;
}

Problem

I am trying to check if the current time is in the range of a specified range. I made a method to check this, but it doesn't work. I'm not sure why not and how to get it to work. ``` private Calendar fromTime; private Calendar toTime; private Calendar currentTime; public boolean checkTime(String time) { try { String[] times = time.split("-"); String[] from = times[0].split(":"); String[] until = times[1].split(":"); fromTime = Calendar.getInstance(); fromTime.set(Calendar.HOUR, Integer.valueOf(from[0])); fromTime.set(Calendar.MINUTE, Integer.valueOf(from[1])); toTime= Calendar.getInstance(); toTime.set(Calendar.HOUR, Integer.valueOf(until[0])); toTime.set(Calendar.MINUTE, Integer.valueOf(until[1])); currentTime = Calendar.getInstance(); currentTime.set(Calendar.HOUR, Calendar.HOUR_OF_DAY); currentTime.set(Calendar.MINUTE, Calendar.MINUTE); if(currentTime.after(fromTime) && currentTime.before(toTime)){ return true; } } catch (Exception e) { return false; } return false; } ``` I am trying to test it like this: ``` if(checkTime("06:00-19:00")){ inRange = true; } ``` The NPE is gone, but it's still not calculating if the time is in the range of `fromTime` to `toTime`. Any help is very much appreciated!

Original source