Generating random date in a specific range in JAVA
Given that your question is unclear, I am expecting you are trying to generate random java.util.Date
with given range.
Please note that java.util.Date
contains date + time information.
Date
in Java is represented by milliseconds from EPOCH. Therefore the easiest way to do what you want is, given d1 and d2 is Date
, and d1 < d2 (in pseudo-code):
Date randomDate = new Date(ThreadLocalRandom.current()
.nextLong(d1.getTime(), d2.getTime()));
If it is actually a "Date" (without time) that you want to produce, which is usually represented by LocalDate
(in Java 8+, or using JODA Time).
It is as easy as, assume d1 and d2 being LocalDate
, with d1 < d2
(pseudo-code):
int days = Days.daysBetween(d1, d2).toDays();
LocalDate randomDate = d1.addDays(
ThreadLocalRandom.current().nextInt(days+1));
Try this
LocalDate startDate = LocalDate.of(1990, 1, 1); //start date
long start = startDate.toEpochDay();
System.out.println(start);
LocalDate endDate = LocalDate.now(); //end date
long end = endDate.toEpochDay();
System.out.println(start);
long randomEpochDay = ThreadLocalRandom.current().longs(start, end).findAny().getAsLong();
System.out.println(LocalDate.ofEpochDay(randomEpochDay)); // random date between the range