DarkCrow
DarkCrow

Reputation: 850

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

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

Upvotes: 3

Views: 921

Answers (2)

Deepak Singh
Deepak Singh

Reputation: 94

You can try the below code

long leftLimit = 1L;
long rightLimit = 3600000L;
long generatedLong = leftLimit + (long) (Math.random() * (rightLimit - leftLimit));

 long currentMillis = System.currentTimeMillis();
 long randomTime = currentMillis + generatedLong;

  Time time = new Time(currentMillis);

I am getting just time but you can get date and time both.

Upvotes: 0

Ryuzaki L
Ryuzaki L

Reputation: 40048

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).

Upvotes: 8

Related Questions