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.