javatimedatetime-comparison

How to check minimum and max times with LocalDateTime java ie minimum 10:00 and max time 10:30


I am new to java and I am having a problem with checking if a time falls/fits into a space of time, ie 10:00-10:30.

The idea is to find out if the time is between 10:00 and 10:30

below is my code:

LocalDateTime timecheck = LocalDate.now().atTime(10, 29);

if(timecheck.getHour() == 10 &&(timecheck.getMinute() <= 30 && timecheck.getMinute() >= 0))
{
      //do something
}

Is there is a way to do this simpler.


Solution

  • Since you only want to check the time, you don't have to use LocalDate or LocalDateTime. The LocalTime class is sufficient.

    You can use LocalTime.isBefore() and LocalTime.isAfter():

    LocalTime timecheck = LocalTime.of(10, 29);
    LocalTime start = LocalTime.of(10, 0);
    LocalTime end = LocalTime.of(10, 30);
    
    if (!start.isAfter(timecheck) && !end.isBefore(timecheck)) {
        ...
    }
    

    Note that this also includes 10:00 and 10:30.