Reputation: 17
I need to randomize a time in java.
If now the time is 24/2/2021 13:56:13
, then I need to randomize a time between 23/2/2021 13:56:13
and 24/2/2021 13:56:13
. I am not familiar to random function in Java so that I maybe need some help. Thank you for your attention.
Upvotes: 0
Views: 740
Reputation: 54148
Take LocalDateTime.now()
then go back in time with a random amount of seconds between 0 and 86400
int randomSeconds = new Random().nextInt(3600 * 24);
LocalDateTime anyTime = LocalDateTime.now().minusSeconds(randomSeconds);
System.out.println(anyTime);
General solution
Define the beginning dates
and end of the period
Compute the difference in seconds and get a random int in that range
Compute the random date with one of these 2 ways:
LocalDateTime periodStart = LocalDateTime.now().minusDays(1);
LocalDateTime periodEnd = LocalDateTime.now();
int randomSeconds = new Random().nextInt((int) periodStart.until(periodEnd, ChronoUnit.SECONDS));
//LocalDateTime anyTime = periodStart.plusSeconds(randomSeconds);
LocalDateTime anyTime = periodEnd.minusSeconds(randomSeconds);
Upvotes: 3