Generate a random LocalDate with java.time

故事扮演 提交于 2019-12-01 05:19:30
Tunaki

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

Try something like this.

public static void main(String[] args) {
    LocalDate start = LocalDate.of(1970, Month.JANUARY, 1);
    long days = ChronoUnit.DAYS.between(start, LocalDate.now());
    LocalDate randomDate = start.plusDays(new Random().nextInt((int) days + 1));
    System.out.println(randomDate);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!