How to get random time within next hour from given time?

DarkCrow :

I have a object which returns DateTime. I need to generate a random time within next hour.

For example

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());
Deadpool :

You can generate random minutes between 0-60 using ThreadLocalRandom and add them to ZonedDateTime

ZonedDateTime result = date.plusMinutes(ThreadLocalRandom.current().nextInt(60));

In the same way you can add randomly generated seconds and nano seconds also

ZonedDateTime result = date.plusMinutes(ThreadLocalRandom.current().nextInt(58))
                               .plusSeconds(ThreadLocalRandom.current().nextLong(59))
                               .plusNanos(ThreadLocalRandom.current().nextLong(999));

Note : nextInt(int bound), nextLong(int bound) will generate between 0 (including) and specific bound (excluding)

Returns a pseudorandom int value between zero (inclusive) and the specified bound (exclusive).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=416012&siteId=1