androidtimeandroid-calendardatetime-comparison

Check if time is between two values - always return 0


I have a function to show an alert if time is between two values.

Eg:

start = 07:00:00

end = 17:00:00

assert start != null;
                        int from = Integer.valueOf(start.replace(":", ""));
                        assert end != null;
                        int to = Integer.valueOf(end.replace(":", ""));
                        Date date = new Date();
                        Calendar c = Calendar.getInstance();
                        c.setTime(date);
                        int t = c.get(Calendar.HOUR_OF_DAY) * 100 + c.get(Calendar.MINUTE);
                        boolean isBetween = to > from && t >= from && t <= to || to < from && (t >= from || t <= to);
                        a = isBetween ? 1 : 0;

                        if(a == 1) { 
                           alert_f();
                           // a is never 1...
                        }

The problem is the a is never 1, even when the actual time is between the start and the end one.

any ideas why?


Solution

  • java.time and ThreeTenABP

        String start = "07:00:00";
        String end = "17:00:00";
        LocalTime startTime = LocalTime.parse(start);
        LocalTime endTime = LocalTime.parse(end);
    
        LocalTime now = LocalTime.now(ZoneId.of("Europe/Rome"));
    
        boolean isBetween = ! now.isBefore(startTime) && now.isBefore(endTime);
        int a = isBetween ? 1 : 0;
        System.out.println("Is between? " + isBetween + "; a = " + a);
    

    When I ran it just now (17:15 in Rome) I got 0 like you, which is expected. If I specify a time zone where it’s not yet 5 PM I get:

    Is between? true; a = 1

    So you need to pick the correct time zone for the code. If you trust the device time zone, you may use ZoneId.systemDefault().

    In my Boolean expression I am using “not before” to mean “equal to or after”.

    I am exploiting the fact that your time strings are in ISO 8601 format, the format that LocalTime and other java.time classes parse (and also print) as their default. So we need no explicit formatter for parsing.

    The date-time classes you were trying to use, Date and Calendar, are long outdated and poorly designed. Also integer values 70 000 and 170 000 don’t really make sense as representations of your start and end times. Instead I am using LocalTime from java.time, the modern Java date and time API. It’s a time of day without date and without UTC offset, so seems to be exactly what you need here.

    Question: Can I use java.time on Android?

    Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

    Links