Close

Java Random - How to create random dates in Java?

Code Snippets Java Random Java 

import java.time.LocalDate;

public class RandomDates {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
LocalDate randomDate = createRandomDate(1900, 2000);
System.out.println(randomDate);
}
}

public static int createRandomIntBetween(int start, int end) {
return start + (int) Math.round(Math.random() * (end - start));
}

public static LocalDate createRandomDate(int startYear, int endYear) {
int day = createRandomIntBetween(1, 28);
int month = createRandomIntBetween(1, 12);
int year = createRandomIntBetween(startYear, endYear);
return LocalDate.of(year, month, day);
}
}

Output

1986-03-17
1960-01-08
1970-07-09
1903-04-06
1996-04-14
1926-06-17
1921-11-18
1943-02-03
1987-02-27
1905-06-13




See Also