I have tried using -
int startSeconds = restaurant.openingTime.toSecondOfDay();
int endSeconds = restaurant.closingTime.toSecondOfDay();
LocalTime timeBetweenOpenClose = LocalTime.ofSecondOfDay(ThreadLocalRandom.current().nextInt(startSeconds, endSeconds));
But this usually runs into an error as in nextInt(origin, bounds), origin can't be less than bounds which will happen if my openingTime
is 16:00:00 and closingTime
is 02:00:00.
You can add the seconds of one day(24*60*60
) when startSeconds
is greater than endSeconds
to represent the next day's second and after getting a random number modulo it by the seconds of one day to convert it into LocalTime by a valid second value.
int secondsInDay = (int)Duration.ofDays(1).getSeconds();
if(startSeconds > endSeconds){
endSeconds += secondsInDay;
}
LocalTime timeBetweenOpenClose = LocalTime.ofSecondOfDay(
ThreadLocalRandom.current().nextInt(startSeconds, endSeconds) % secondsInDay);
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