我有一个返回 DateTime 的对象。我需要在下一小时内生成一个随机时间。
例如
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());
最佳答案
您可以使用 ThreadLocalRandom 生成 0-60
之间的随机分钟数并将它们添加到 ZonedDateTime
ZonedDateTime result = date.plusMinutes(ThreadLocalRandom.current().nextInt(60));
以同样的方式,您也可以添加随机生成的秒和纳秒
ZonedDateTime result = date.plusMinutes(ThreadLocalRandom.current().nextInt(58))
.plusSeconds(ThreadLocalRandom.current().nextLong(59))
.plusNanos(ThreadLocalRandom.current().nextLong(999));
注意: nextInt(intbound)、nextLong(intbound)将生成0(含)和特定边界(不含)之间的值
Returns a pseudorandom int value between zero (inclusive) and the specified bound (exclusive).
关于java - 如何获得给定时间下一小时内的随机时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59970663/