Wei Jun Tee
Wei Jun Tee

Reputation: 17

How can randomize a time between yesterday and today's local DateTime in java?

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

Answers (1)

azro
azro

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

  1. Define the beginning dates and end of the period

  2. Compute the difference in seconds and get a random int in that range

  3. Compute the random date with one of these 2 ways:

    • Go from the beginning and add the random amount of seconds
    • Go from the end and remove the random amount of seconds
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

Related Questions