In this article, we will see how to generate a random date between two dates in Java.
In Java, we can use the java.time.LocalDate
to represent a date without a time component and this along with java.time.temporal.ChronoUnit
we can calculate the duration between two dates and generate a random date between two dates.
Let us first import all the required packages as shown below.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.ThreadLocalRandom;
In the following example, I set the start date to January 1, 2022, and the end date to December 31, 2022. Maybe you can modify these dates with your desired range. You can also get input from the user or external sources.
LocalDate startDate = LocalDate.of(2022, 1, 1);
LocalDate endDate = LocalDate.of(2022, 12, 31);
Now, to generate a random date between the above two dates, first, we need to calculate the duration between these two dates. That can be easily done using the ChronoUnit.DAYS
enum. This will give us the number of days between the two dates.
long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
We need to generate a random number of days within the calculated duration using the ThreadLocalRandom.current().nextLong()
method and we can add these random days to the start date.
long randomNumberOfDays = ThreadLocalRandom.current().nextLong(daysBetween + 1);
Finally, as shown below add the randomly generated days to the start date to get a random date within the specified range.
LocalDate randomDate = startDate.plusDays(randomNumberOfDays);