我试过使用 -
int startSeconds = restaurant.openingTime.toSecondOfDay();
int endSeconds = restaurant.closingTime.toSecondOfDay();
LocalTime timeBetweenOpenClose = LocalTime.ofSecondOfDay(ThreadLocalRandom.current().nextInt(startSeconds, endSeconds));
但这通常会遇到错误,如 nextInt(origin, bounds), origin 不能小于 bounds,如果我的 openingTime
是 16:00:00 并且 closingTime
是02:00:00。
答案 0 :(得分:5)
当24*60*60
大于startSeconds
时,可以加上一天的秒数(endSeconds
)来表示第二天的秒数,得到一个随机数取模后的秒数一天通过有效的第二个值将其转换为 LocalTime。
int secondsInDay = (int)Duration.ofDays(1).getSeconds();
if(startSeconds > endSeconds){
endSeconds += secondsInDay;
}
LocalTime timeBetweenOpenClose = LocalTime.ofSecondOfDay(
ThreadLocalRandom.current().nextInt(startSeconds, endSeconds) % secondsInDay);
答案 1 :(得分:5)
如果不应用日期和时区,我们将无法知道下午 4 点到凌晨 2 点之间将经过多长时间。因此,我们将使用 ZonedDateTime
解决它。
LocalDate#atStartOfDay
获取 ZonedDateTime
ZoneId zoneId = ZoneId.systemDefault();
LocalDate.now().atStartOfDay(zoneId);
ZonedDateTime#with
获取具有指定时间的 ZonedDateTime
。ZonedDateTime#toInstant
从 Instant
派生 ZonedDateTime
。Instant
后,您可以使用 ThreadLocalRandom.current().nextLong
在开始和结束 {{1} 的范围内生成 long
值}s 并使用获取的值来获取所需的 Instant
。Instant#atZone
从此 Instant
派生出 ZonedDateTime
,然后使用 ZonedDateTime#toLocalTime
获取所需的时间。演示:
Instant
从 Trail: Date Time 了解有关现代日期时间 API 的更多信息。
ONLINE DEMO 随机打印 100 次。