I am trying to generate the random date between 01/01/2016 to 01/01/2017 using Java. I want to date should be in DD/MM/YYYY format. Your help would be appreciated. My requirement is to generate date DD/MM/YYYY then convert into string.
If using Java 8 I'd suggest using the new java.time
API:
LocalDate from = LocalDate.of(2016, 1, 1);
LocalDate to = LocalDate.of(2017, 1, 1);
long days = from.until(to, ChronoUnit.DAYS);
long randomDays = ThreadLocalRandom.current().nextLong(days + 1);
LocalDate randomDate = from.plusDays(randomDays);
System.out.println(randomDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
Change days + 1
to days
if you do not want to randomly generate 01/01/2017 i.e. the end date is exclusive.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments