0

My input string is "mmyy" date format, I want to be able to replace that string with a random date with same format "mmyy" but the year has to be before 2010. What should I do? any suggestion? Do I have to set up SimpleDateFormat?

example: input: "0914" , my output should be random it and return a string like "0802" where "02" is 2002 which is before 2010.

Thanks

RLe
  • 456
  • 12
  • 28
  • Use Java 8's Time API or JodaTime – MadProgrammer Jul 01 '15 at 22:48
  • 2
    You could generate two random int, the 1st one < 10 (year) and the 2nd one <= 12 (month), then concat to one string filling it with 0's if necessary to get a string similar to XXYY, then to format it to get a date... – Alex S. Diaz Jul 01 '15 at 22:54
  • possible duplicate of [Generate random date of birth](http://stackoverflow.com/questions/3985392/generate-random-date-of-birth) – Basil Bourque Jul 01 '15 at 23:32

1 Answers1

2

Try the following snippet for a Java 8 version:

// Generate random date
Random random = new Random();
LocalDate maxDate = LocalDate.of(2010, 1, 1);
long randomDay = random.nextInt((int) maxDate.toEpochDay());
LocalDate randomDate = LocalDate.ofEpochDay(randomDay);

// Convert to String using 'MMyy' pattern
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMyy");
String result = dtf.format(randomDate.atStartOfDay());

System.out.println(result);

Note 1: That should generate a random date between 1Jan1970 and 1Jan2010 (excluding) - is this what you wanted?

Note 2: The date format is fixed and known a priori the way you stated it. So there is no need for the input string to "replace", just use result (unless I misunderstood?)

Note 3: See my answer to a more general (and possibly duplicate) question. You'll also find pre-Java 8 ideas there.

Community
  • 1
  • 1
Jens Hoffmann
  • 6,699
  • 2
  • 25
  • 31
  • I'm curious (but the author didn't mention it) if she is using strings only, is she limited to dates after 2000 to avoid ambiguity?.... – Alex S. Diaz Jul 02 '15 at 00:18
  • 1
    @JensHoffman Yours is an excellent Answer. But better to add that Answer to the original Question rather than the later duplicate. The original [idea behind StackOverflow](http://www.joelonsoftware.com/items/2008/09/15.html) was to create a Wikipedia-style collection of good questions with good answers rather than scattered discussion threads. Duplicates like this Question should be left to dry up and shrivel away, or be deleted/retracted. – Basil Bourque Jul 02 '15 at 00:28
  • @BasilBourque Thanks for your comment, understood. I left a similar answer on the [original question](http://stackoverflow.com/questions/3985392/generate-random-date-of-birth) as well, so the information is retained in case this question gets closed. – Jens Hoffmann Jul 02 '15 at 19:26