RLe
RLe

Reputation: 486

Generate date before certain time?

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

Upvotes: 0

Views: 121

Answers (1)

Jens Hoffmann
Jens Hoffmann

Reputation: 6801

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.

Upvotes: 2

Related Questions