-5

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.

Akki
  • 59
  • 2
  • 11

4 Answers4

4

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.

Markus Benko
  • 1,507
  • 8
  • 8
1

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.

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
1

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() ) );
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

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());
Fabien Leborgne
  • 377
  • 1
  • 5