Vaishak Babu
Vaishak Babu

Reputation: 53

How to generate random time for current date?

When i convert to milliseconds the time shows different time for different DATES. How can i generate the same time for current date.

CODE:

final Random random = new Random();
for (int i = 0; i < 10; i++) {
final LocalTime time = new LocalTime(random.nextLong());
System.out.println(time);
}

Thanks in advance.

Upvotes: 2

Views: 6011

Answers (3)

Andreas
Andreas

Reputation: 159086

Assuming the LocalTime you're using is org.joda.time.LocalTime, not java.time.LocalTime (can't be), and you want the random time-of-day with todays date, just call toDateTimeToday().

DateTime datetime = time.toDateTimeToday();

Upvotes: 0

london-deveoper
london-deveoper

Reputation: 543

If i have understood your question correctly you can do something like the following

MillisecondsToStartOfTodayFromEpoch + (timeOtherDateInMilliseconds % MilliSecondsPerDay)

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201437

First, get the LocalDate for now and then add a random LocalTime with a random value for hours (0-24], minutes (0-60], seconds (0-60] and nanoseconds (0, 999999999]. Then display your LocalDateTime. Like,

for (int i = 0; i < 10; i++) {
    LocalDateTime time = LocalDateTime.of(LocalDate.now(), 
            LocalTime.of(random.nextInt(24), random.nextInt(60),
            random.nextInt(60), random.nextInt(999999999 + 1)));
    System.out.println(time);
}

Upvotes: 3

Related Questions