Search code examples
javarandomtimejava-timelocaltime

How to generate a random time between two times say 4PM and 2AM?


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.


Solution

  • 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);