1

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);
}
Than
  • 21
  • 4
  • What do you mean with "Duration conflicts with Period"? I don't see `Duration` in your code (only `Period`). – knittl May 07 '21 at 17:47

2 Answers2

2
    Instant now = Instant.now();
    Instant then = now.minus(2685, ChronoUnit.DAYS);
    long millisBetween = ChronoUnit.MILLIS.between(then, now);
    Instant randomTime = then.plusMillis(ThreadLocalRandom.current().nextLong(millisBetween));
    
    System.out.println(randomTime);

Example output:

2019-09-13T10:21:21.078242Z

If you don’t want the fraction of second:

    System.out.println(randomTime.truncatedTo(ChronoUnit.SECONDS));

2019-09-13T10:21:21Z

I find it simpler to draw just one random number and let it decide the date and time rather than drawing the day and the time separately. ThreadLocalRandom has the advantage over Random of offering the option to draw a random long with a bound. Also tis way has the theoretical possibility of producing a time today, but only in the part of the day that has already passed.

I am exploiting the fact that the format you asked for agrees with what Instant produces from its toString method. The format is known as ISO 8601 and is an international standard (ISO is for International Organization for Standardization).

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
1

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);
}
Eugene
  • 117,005
  • 15
  • 201
  • 306