We cannot know how much time will elapse between 4 PM and 2 AM without applying a date and time zone. Therefore, we will solve it using ZonedDateTime
.
- The first step will be: obtain a
ZonedDateTime
by calling LocalDate#atStartOfDay
ZoneId zoneId = ZoneId.systemDefault();
LocalDate.now().atStartOfDay(zoneId);
- Next, use
ZonedDateTime#with
to get a ZonedDateTime
with the specified time.
- Now, you can derive an
Instant
from a ZonedDateTime
using ZonedDateTime#toInstant
.
- Once you have the start and end
Instant
s derived this way, you can use ThreadLocalRandom.current().nextLong
to generate a long
value in the range of the start and the end Instant
s and use the obtained value to get the required Instant
.
- Finally, you can derive a
ZonedDateTime
from this Instant
using Instant#atZone
and then get the required time using ZonedDateTime#toLocalTime
.
Demo:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.concurrent.ThreadLocalRandom;
public class Main {
public static void main(String[] args) {
// Change it as per the applicable timezone e.g. ZoneId.of("Europe/London")
ZoneId zoneId = ZoneId.systemDefault();
LocalDate today = LocalDate.now();
ZonedDateTime zdtStart = today.atStartOfDay(zoneId)
.with(LocalTime.of(16, 0));
ZonedDateTime zdtEnd = today.plusDays(1)
.atStartOfDay(zoneId)
.with(LocalTime.of(2, 0));
ZonedDateTime zdtResult =
Instant.ofEpochMilli(
ThreadLocalRandom
.current()
.nextLong(
zdtStart.toInstant().toEpochMilli(),
zdtEnd.toInstant().toEpochMilli()
)
).atZone(zoneId);
LocalTime time = zdtResult.toLocalTime();
System.out.println(time);
}
}
Learn more about the modern date-time API from Trail: Date Time.
ONLINE DEMO printing 100 random times.
restaurant.openingTime
andrestaurant.closingTime
arejava.time.LocalTime
too? – Edwardedwardian