I\'m writing some code to populate a MySQL database with random data for testing purposes. I need to populate a DATE
column with random dates from 1970-2015.
A simple way is to convert the minimum and maximum date to their corresponding epoch day, generate a random integer between those two values and finally convert it back to a LocalDate
. The epoch day is obtained with toEpochDay() which is the count of days since 1970-01-01 (ISO).
The problem with generating a random year, then month and then day is that you have a small chance of falling with an invalid date (like 31st of February). Also, taking a random epoch day guarantees a uniform distribution across all possible dates.
public static void main(String... args) {
long minDay = LocalDate.of(1970, 1, 1).toEpochDay();
long maxDay = LocalDate.of(2015, 12, 31).toEpochDay();
long randomDay = ThreadLocalRandom.current().nextLong(minDay, maxDay);
LocalDate randomDate = LocalDate.ofEpochDay(randomDay);
System.out.println(randomDate);
}
Note that since the minimum date is actually the very first, you could replace it with 0.
To convert this LocalDate
into a java.sql.Date
, you can refer to this post:
java.sql.Date date = java.sql.Date.valueOf(randomDate);