Generate a random LocalDate with java.time

前端 未结 2 1109
一生所求
一生所求 2021-01-11 17:16

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.

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-11 17:56

    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);
    

提交回复
热议问题