0

I want to generate a random date as string in format - yy-MM-dd for the given year.

assume if i pass the year it should give a random date of the year.

I went through Random() as well as nextInt() but not sure how to get this

could you please help me on how to achieve this?

Thanks.

prathibha
  • 43
  • 4
  • 2
    Try: http://stackoverflow.com/questions/3985392/generate-random-date-of-birth – Tom Jan 20 '15 at 10:58

3 Answers3

3

You can use a Calendar to do that:

final Calendar cal = Calendar.getInstance();
final Random rand = new Random();
final SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd");

cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.DAY_OF_YEAR, rand.nextInt(cal.getActualMaximum(Calendar.DAY_OF_YEAR)) + 1);

System.out.println(format.format(cal.getTime()));

cal.getActualMaximum(Calendar.DAY_OF_YEAR) will return the number of the last day of the year the Calendar is set to (2014 in this code).

rand.nextInt() will return a number between 0 (inclusive) and the number of the last day (exclusive). You have to add 1 because the field Calendar.DAY_OF_YEAR starts at 1.

cal.set() will set the given field of the Calendar to the value given as the second argument. It is used here to set the year to 2014, and the day of the year to the random value.

SimpleDateFormat is used to print the date in the required format.

Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
3

You can do with JSR-310 (Built in Java 8, but available to older versions)

public static LocalDate randomDateIn(int year) {
    Year y = Year.of(year);
    return y.atDay(1+new Random().nextInt(y.length()));
}

System.out.println(randomDateIn(2014));

prints something like

2014-05-21
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
-1

If you want to work with random, this is how it works:

Random r=new Random();

int day=r.nextInt(30)+1;   // (think of something yourself for implementing months with different amount of days)
int month=r.nextInt(11)+1; // (+1 because you don't want the zero)

However i see another answer, which if it works will probably save you a lot of time on implementing the days each month has.(and the leap year)

Bart Hofma
  • 644
  • 5
  • 19