Java: generate random Date between now minus X months plus Y months
Introduction
This blogpost shows a Java 8+ code example on how to generate a timestamp between two months relative to today ("now").
The code
This example code creates a random java.util.Date between 12 months ago from today until 1 month ahead from today, which will be available in variable randomDate.
LocalDateTime nowMinusYear = LocalDateTime.now().minusMonths(12);
ZonedDateTime nowMinusYearZdt = nowMinusYear.atZone(ZoneId.of("Europe/Paris"));
beginTimeInMilliseconds = nowMinusYearZdt.toInstant().toEpochMilli();
LocalDateTime nowPlusMonth = LocalDateTime.now().plusMonths(1);
LocalDateTime nowPlusMonth = LocalDateTime.now().plusMonths(1);
ZonedDateTime nowPlusMonthZdt = nowPlusMonth.atZone(ZoneId.of("Europe/Paris"));
endTimeInMilliseconds = nowPlusMonthZdt.toInstant().toEpochMilli();
System.out.println("System.out.currentInmillis = " + System.currentTimeMillis() + ", beginTimeInMilliseconds = " + beginTimeInMilliseconds + ", endTimeInMilliseconds = " + endTimeInMilliseconds);
Date randomDate = new Date(getRandomTimeInMillisBetweenTwoDates());
...
...
private static long getRandomTimeInMillisBetweenTwoDates() {
long diff = endTimeInMilliseconds - beginTimeInMilliseconds + 1;
return beginTimeInMilliseconds + (long) (Math.random() * diff);
}
Reference: https://stackoverflow.com/questions/23944370/how-to-get-milliseconds-from-localdatetime-in-java-8
No comments:
Post a Comment