如何在下午 4 点和凌晨 2 点之间的两个时间生成随机时间?

时间:2021-04-03 10:43:36

标签: java random time java-time localtime

我试过使用 -

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。

2 个答案:

答案 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 解决它。

  1. 第一步是:通过调用 LocalDate#atStartOfDay 获取 ZonedDateTime
ZoneId zoneId = ZoneId.systemDefault();
LocalDate.now().atStartOfDay(zoneId);
  1. 接下来,使用 ZonedDateTime#with 获取具有指定时间的 ZonedDateTime
  2. 现在,您可以使用 ZonedDateTime#toInstantInstant 派生 ZonedDateTime
  3. 以这种方式派生开始和结束 Instant 后,您可以使用 ThreadLocalRandom.current().nextLong 在开始和结束 {{1} 的范围内生成 long 值}s 并使用获取的值来获取所需的 Instant
  4. 最后,您可以使用 Instant#atZone 从此 Instant 派生出 ZonedDateTime,然后使用 ZonedDateTime#toLocalTime 获取所需的时间。

演示:

Instant

Trail: Date Time 了解有关现代日期时间 API 的更多信息。

ONLINE DEMO 随机打印 100 次。

相关问题