Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate a random date within some days back from today

I am trying to generate a random date in yyyy-mm-dd format for the following cases.

  1. The random date should be within 90 days range from today.
  2. The random date should be within 90 to 180 days from today.
  3. 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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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.

>Solution :

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:

  1. getRandomDateInFutureDaysRange(0, 90)
  2. getRandomDateInFutureDaysRange(90, 180)
  3. 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading