How to generate random dates in a specific range in JAVA? I have seen How do I generate random integers within a specific range in Java? link which is to generate random numbers.Is there similar/other kind of way to generate random date in JAVA?
Asked
Active
Viewed 4.1k times
11
-
Just create a date from a random timestamp. – shmosel Oct 26 '16 at 04:01
-
Please search Stack Overflow thoroughly before posting. – Basil Bourque Oct 26 '16 at 06:47
3 Answers
21
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));

Adrian Shum
- 38,812
- 10
- 83
- 131
-
2In Java 8, you must first get an instance of ThreadLocalRandom to call nextLong method. **ThreadLocalRandom.current()** Example would be like this: `Date randomDate = new Date(ThreadLocalRandom.current().nextLong(d1.getTime(), d2.getTime()));` – Imtiaz Shakil Siddique Nov 27 '18 at 06:41
-
1@ImtiazShakilSiddique thanks for spotting the mistake. It is actually the case even before JDK8. Lemme fix it – Adrian Shum Nov 27 '18 at 06:51
11
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

Saravana
- 12,647
- 2
- 39
- 57
-
2Why not use `ThreadLocalRandom.current().nextLong(start, end)` instead of creating a stream? – Tvaroh Dec 01 '17 at 16:06
7
You can do something like this
long random = ThreadLocalRandom.current().nextLong(startDate.getTime(), endDate.getTime());
Date date = new Date(random);

ravthiru
- 8,878
- 2
- 43
- 52