如何获得给定时间下一小时内的随机时间?

Dar*_*row 2 java datetime date

我有一个返回日期时间的对象。我需要在下一小时内生成一个随机时间。

例如

ZonedDateTime date1 = ZonedDateTime.now(); // returns  2020-01-29T15:00:00.934
ZonedDateTime date2 = ZonedDateTime.now(); // returns  2020-01-29T15:45:00.233
ZonedDateTime convertedDate1;
ZonedDateTime convertedDate2;

//Conversion logic

assertEquals("2020-01-29T15:37:56.345", convertedDate1.toString());
assertEquals("2020-01-29T16:22:22.678", convertedDate2.toString());
Run Code Online (Sandbox Code Playgroud)

Dea*_*ool 7

0-60您可以在使用ThreadLocalRandom之间生成随机分钟并将它们添加到ZonedDateTime

ZonedDateTime result = date.plusMinutes(ThreadLocalRandom.current().nextInt(60));
Run Code Online (Sandbox Code Playgroud)

以同样的方式,您也可以添加随机生成的秒和纳秒

ZonedDateTime result = date.plusMinutes(ThreadLocalRandom.current().nextInt(58))
                               .plusSeconds(ThreadLocalRandom.current().nextLong(59))
                               .plusNanos(ThreadLocalRandom.current().nextLong(999));
Run Code Online (Sandbox Code Playgroud)

注意: nextInt(intbound)、nextLong(intbound)将在0(含)和特定边界(不含)之间生成

返回介于零(含)和指定界限(不包括)之间的伪随机 int 值。