Fragment for a solution based on Java 8:
Random random = new Random(); int minDay = (int) LocalDate.of(1900, 1, 1).toEpochDay(); int maxDay = (int) LocalDate.of(2015, 1, 1).toEpochDay(); long randomDay = minDay + random.nextInt(maxDay - minDay); LocalDate randomBirthDate = LocalDate.ofEpochDay(randomDay); System.out.println(randomBirthDate);
Note This creates a random date between 1Jan1900 (inclusive) and 1Jan2015 (exclusive).
Note It is based on the days of the era , i.e. days relative to 1Jan1970 ( EPOCH ) - positive value after EPOCH, negative value before EPOCH
You can also create a small utility class:
public class RandomDate { private final LocalDate minDate; private final LocalDate maxDate; private final Random random; public RandomDate(LocalDate minDate, LocalDate maxDate) { this.minDate = minDate; this.maxDate = maxDate; this.random = new Random(); } public LocalDate nextDate() { int minDay = (int) minDate.toEpochDay(); int maxDay = (int) maxDate.toEpochDay(); long randomDay = minDay + random.nextInt(maxDay - minDay); return LocalDate.ofEpochDay(randomDay); } @Override public String toString() { return "RandomDate{" + "maxDate=" + maxDate + ", minDate=" + minDate + '}'; } }
and use it as follows:
RandomDate rd = new RandomDate(LocalDate.of(1900, 1, 1), LocalDate.of(2010, 1, 1)); System.out.println(rd.nextDate()); System.out.println(rd.nextDate());
Jens Hoffmann Jul 02 '15 at 19:17 2015-07-02 19:17
source share