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

标签 java datetime date

我有一个返回 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/

相关文章:

python - 使用Python从MySQL数据库中提取两个日期时间之间的数据

c# - 计算一个月的最后一天

c++ - boost::gregorian::date 没有 `set-type` 函数?

Java日期和时间转换

java - 如何允许 Sprite 只从一侧移动到另一侧?

java - 使变量 volatile 是否可以消除 : Multithreaded correctness - Inconsistent synchronization

java - Interrupted 与 isInterrupted 实现

java - webdriver中使用TestNG框架实现登录

date - D3 直方图 - 基于日期

postgresql - 如何在 postgresql 插入查询中插入当前日期时间