'Random date generation in Java that is any date 26 days ago from today

I want to write a code wherein I can generate a random date between 26 days ago from today's date. That is, if today's date is 12th April, I wanted my code to generate any date from 17th of March to 12th of April means 17th April is 26 days ago from 12th April.

How to write this in Java? Can anyone help?

package apiActions;
import java.time.LocalDate;

    public class RandomDates {
        public static void main(String[] args) {
            //for (int i = 0; i < 10; i++) {
                LocalDate randomDate = createRandomDate(2022, 2022);
                System.out.println(randomDate);
                System.out.println(randomDate.minusDays(26));
           // }
        }
    
        public static int createRandomIntBetween(int start, int end) {
            return start + (int) Math.round(Math.random() * (end - start));
        }
    
        public static LocalDate createRandomDate(int startYear, int endYear) {
            int day = createRandomIntBetween(1, 31);
            int month = createRandomIntBetween(1, 4);
            int year = createRandomIntBetween(startYear, endYear);
            return LocalDate.of(year, month, day);
        }
    }

Tried this but I am not getting how to modify. Also I want date in the format yyyy-mm-dd.



Solution 1:[1]

Get today’s date. Subtract a random number of days. Call toString to generate text in standard ISO 8601 format of YYYY-MM-DD.

LocalDate
.now()                   // Better to specify explicitly your desired time zone. If omitted, the JVM’s current default time zone is implicitly applied. 
.minusDays( 
    ThreadLocalRandom
    .current()
    .nextLong( 0 , 27 )  // ( inclusive , exclusive ). So 0,27 for 0 through 26. 
)                        // Returns another `LocalDate` object. 
.toString()              // Generates text in standard ISO 8601 format. 

See this code run live at IdeOne.com.

2022-03-31

Solution 2:[2]

Well, here is one way. Just get the current day and subtract 0 to 26 days.

Random r= new Random();
LocalDate ldt = LocalDate.now().minusDays(r.nextLong(27));
System.out.println(ldt);

Prints something like

2022-04-11

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 WJS