javaandroidtimehourjava.util.calendar

How can I compare hours?


I am building an app, and I need to know how to compare two hours.

For example, my store opens at 6:30 AM and closes at 5:00 PM.

I need to show in a TextView that after 5 PM my store is closed, and after 6:30 AM my store is open, from Monday to Friday.

How can I do this? This is my attempt:

public void timer() {
    Calendar c = Calendar.getInstance();
    int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
    int open = 6:30; // 1 ERROR HERE WITH ":"
    int close = 17;

    if (timeOfDay < close) {
        hour.setText.("OPEN");
    }
}

But I am getting multiple errors. One in int open when I put 06:30 with ":"; two with limit of Monday to Friday.

Thanks for the help.


Solution

  • You should be using the Java 8 Date & Time library, because Calendar and Date are obsolete.

    The LocalTime class should be sufficient.

    LocalTime open = LocalTime.of(6, 30);
    LocalTime closed = LocalTime.of(17, 0);
    
    LocalTime currentTime = LocalTime.now();
    if (currentTime.isBefore(open) || currentTime.isAfter(closed)) {
        // Closed
    }
    

    You could then use the DateTimeFormatter class to format the time into the desired format.

    If you want to also take the day of the week into consideration while determining the opening times of your shop, then you could use LocalDateTime in conjunction with abovementioned example:

    LocalDateTime now = LocalDateTime.now();
    
    // The opening days. Static import these from java.time.DayOfWeek
    Set<DayOfWeek> daysOpen = new HashSet<>(Arrays.asList(
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY));
    // Opening and closing times
    LocalTime timeOpen = LocalTime.of(6, 30);
    LocalTime timeClosed = LocalTime.of(17, 0);
    
    if (!daysOpen.contains(now.getDayOfWeek()) || now.toLocalTime().isBefore(timeOpen) || now.toLocalTime().isAfter(timeClosed)) {
        System.out.println("Closed");
    }
    else {
        System.out.println("Open");
    }