I want to get a date that generates the time from now to 2685 days back and a random time. The format I accept must be “uuuu-MM-dd’T’HH: mm: ssZ”. Currently my program is generating a random date but I am not able to create a random time because Duration conflicts with Period
public static String generateRandomDateAndTimeInString() { LocalDate date = LocalDate.now() .minus(Period.ofDays((new Random().nextInt(2685)))); return formatDate(date); } public static String formatDate(LocalDate date) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ"); return date.atStartOfDay().atOffset(ZoneOffset.UTC).format(dtf); }
Advertisement
Answer
Something like this may be?
public static String generateRandomDateAndTimeInString() { ThreadLocalRandom random = ThreadLocalRandom.current(); LocalDate date = LocalDate.now() .minus(Period.ofDays((random.nextInt(2685)))); LocalTime time = LocalTime.of(random.nextInt(0, 23), random.nextInt(0, 59), random.nextInt(0, 59)); return formatDate(LocalDateTime.of(date, time)); } public static String formatDate(LocalDateTime date) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ"); return date.atOffset(ZoneOffset.UTC).format(dtf); }