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.
-
MS SQL YOU CAN TRY ORDER BY NEWID() – Singh Kailash Mar 01 '17 at 12:42
-
Just create a random number between 1 to 367 and then map it to corresponding date – apomene Mar 01 '17 at 12:43
-
I have tried that but the solutions are mentioned there does not fulfill my requirements. – Akki Mar 01 '17 at 12:43
-
@apomene could you please write it here? So I can try. – Akki Mar 01 '17 at 12:44
4 Answers
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.

- 1,507
- 8
- 8
-
@FlorentBayle Thanks for mentioning, I have changed the code accordingly. – Markus Benko Mar 01 '17 at 13:09
-
Get a random number between 0 and 365 (2016 had 366 days), then add this number of days to the date 1/1/2016
.
You can add days to the date directly if using some time library, or add them by converting java's Date to long and then back after you add it.
Then print the result in whichever format you need.
If you need help with some specific step of this process, you should probably specify your question more clearly.

- 12,211
- 5
- 29
- 43
The correct accepted Answer by Benko is correct but could be simpler is we want the entire year rather than arbitrary dates.
The Year
class represents a year, and offers some handy methods. We can obtain a date by specifying a day-of-year 1-365 (or 366 in Leap Year).
We need a random day-of-year. The ThreadLocalRandom
class provides a thread-safe (safe if always accessed via .current()
) random number generator. We specify an origin of 1 for the first day of year and a bound of the length of the year for the lady day of the year.
Year y = Year.of( 2016 );
LocalDate ld = y.atDay( ThreadLocalRandom.current().nextInt( 1 , y.length() ) );

- 303,325
- 100
- 852
- 1,154
You could do that using calendar to initialize your date then adding a day between 0 to 365 as follow:
Calendar calendar = Calendar.getInstance();
calendar.set(2016, 0, 0);
calendar.set(Calendar.DAY_OF_YEAR, new Random().nextInt() % 365);
new SimpleDateFormat("dd/MM/yyyy").format(calendar.getTime());

- 377
- 1
- 5
-
The troublesome `Calendar` class and its siblings are now legacy, supplanted by the java.time classes. – Basil Bourque Mar 01 '17 at 18:09