B
B
BespoyasovaV2021-01-29 22:02:23
Java
BespoyasovaV, 2021-01-29 22:02:23

Is there a method in java that generates a random date?

Is there a method in java that generates a random date?
If there is, then which one?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-01-29
@BespoyasovaV

There is.
instant.now(); - always new date. It has never been repeated.
It's also possible like this:

public static void main(String[] args) {
        long leftLimit = 0L; // 01/01/1970, 00:00
        long rightLimit = Instant.now().toEpochMilli(); // now
        long generatedLong = leftLimit + (long) (Math.random() * (rightLimit - leftLimit));
        var randomDate = Instant.ofEpochMilli(generatedLong);

        DateTimeFormatter formatter =
                DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
                        .withZone( ZoneId.systemDefault() );

        System.out.println( formatter.format( randomDate ));
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question