I am trying to generate a random date in yyyy-mm-dd format for the following cases.
- The random date should be within 90 days range from today.
- The random date should be within 90 to 180 days from today.
- The random date should be within 181 to 270 days from today.
I have written a short code snippet wherein I tried generating a random date but it does not give me the date in the range expected. That is between Sep 9 and Jan 14. It gives me the dates beyond Jan 14 also.
`public static void generateRandomDate() { Date d1=new Date(2022, 9, 9); Date d2=new Date(2023, 1, 14);
Date randomDate = new Date(ThreadLocalRandom.current()
.nextLong(d1.getTime(), d2.getTime()));
System.out.println(randomDate);
}`
Output: Wed Jan 17 23:41:37 IST 3923 I can use switch case to generate random dates according to the cases I want. But I am not able to get the desired date with the code I am trying and also I need to date to be in yyyy-mm-dd format. It will be really helpful if I will be able to pass the d1 and d2 in that format.
CodePudding user response:
First of all, you should rather use a LocalDate
instead of Date
.
But going back to your question.
Current date can be obtained from:
LocalDate today = LocalDate.now();
And right now, you need to add appropriate number of days. If your case, you can create method:
private LocalDate getRandomDateInFutureDaysRange(int start, int end) {
LocalDate today = LocalDate.now();
return today.plusDays(ThreadLocalRandom.current().nextLong(start, end));
}
For your use cases you can call it as follows:
- getRandomDateInFutureDaysRange(0, 90)
- getRandomDateInFutureDaysRange(90, 180)
- getRandomDateInFutureDaysRange(181, 270)
To format the date you can use DateTimeFormatter
as follows:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = yourDateToFormat.format(formatter);