Search code examples
javajava-timelocaldatedatetime-comparison

Java LocalDate / LocalDateTime - Hour Between


How do I know if an hour is between two schedules?

Example:

10:00 is between 8:00 and 12:00?
7:30 is between 8:00 and 12:00?

I'm trying this way:

LocalDateTime s = LocalDateTime.of (2017, 10, 20, 8, 00);
LocalDateTime f = LocalDateTime.of (2017, 10, 20, 12, 00);

LocalDate test = LocalDate.of (2017, 10, 20, 10, 00); (<- Must be LocalDate)

if ((test.isAfter (s)) && (test.isBefore (s))
   return true;
else
   return false;

It's returning the following error:

The method isBefore (ChronoLocalDateTime ) In the type LocalDateTime is not applicable for the arguments (LocalTime)


Solution

  • Why include dates if you are only interested in times?

    LocalTime s = LocalTime.of (8, 0);
    LocalTime f = LocalTime.of (12, 0);
    
    LocalTime test = LocalTime.of (10, 0);
    
    if (test.isAfter (s) && test.isBefore (f))
    

    And if you received a LocalDateTime, you can call ldt.toLocalTime().