Please suggest if there is an API support to determine if my time is between 2 LocalTime
instances, or suggest a different approach.
I have this entity:
class Place {
LocalTime startDay;
LocalTime endDay;
}
which stores the working day start and end time, i.e. from '9:00' till '17:00', or a nightclub from '22:00' till "5:00".
I need to implement a Place.isOpen()
method that determines if the place is open at a given time.
A simple isBefore
/isAfter
does not work here, because we also need to determine if the end time is on the next day.
Of course, we can compare the start and end times and make a decision, but I want something without additional logic, just a simple between()
call. If LocalTime
is not sufficient for this purpose, please suggest other.
LocalTime is an immutable date-time object that represents a time, often viewed as hour-minute-second. Time is represented to nanosecond precision.
In Java 8, we can use Period , Duration or ChronoUnit to calculate the difference between two LocalDate or LocaldateTime . Period to calculate the difference between two LocalDate . Duration to calculate the difference between two LocalDateTime . ChronoUnit for everything.
LocalTime now() method in Java with Examples The now() method of the LocalTime class in Java is used to get the current time from the system clock in the default time-zone. Parameters: This method does not accept any parameter.
LocalTime is an immutable date-time object that represents a time, often viewed as hour-minute-second. Time is represented to nanosecond precision. For example, the value "13:45.30.123456789" can be stored in a LocalTime. This class does not store or represent a date or time-zone.
Use LocalDate ‘s plusDays () and minusDays () method to get the next day and previous day, by adding and subtracting 1 from today. Use Date class constructor and pass the time in milliseconds. To get the time for yesterday, get the time for today and subtract total milliseconds in a day.
Java is the most popular programming language and widely used programming language. Java is used in all kinds of applications like mobile applications, desktop applications, web applications. As in Java, java.time.LocalTime class represents time, which is viewed as hour-minute-second.
Use LocalDate ‘s plusDays () and minusDays () method to get the next day and previous day, by adding and subtracting 1 from today. Use Date class constructor and pass the time in milliseconds.
If I understand correctly, you need to make two cases depending on whether the closing time is on the same day as the opening time (9-17) or on the next day (22-5).
It could simply be:
public static boolean isOpen(LocalTime start, LocalTime end, LocalTime time) {
if (start.isAfter(end)) {
return !time.isBefore(start) || !time.isAfter(end);
} else {
return !time.isBefore(start) && !time.isAfter(end);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With