본문 바로가기
▶ Back-End/Java

Random LocalDate 생성

by 오늘도 코딩 2023. 9. 21.
728x90
반응형

원하는 기간의 Random LocalDate 생성

 

 

/**
 * getRandomDate
 * 
 * @param String(yyyyMMdd)
 * @param String(yyyyMMdd)
 * @return LocalDate(yyyy-MM-dd)
 */
public LocalDate getRandomDate(String startDate, String endDate) {
    LocalDate fromDate = LocalDate.of(
            Integer.parseInt(startDate.substring(0, 4)),
            Integer.parseInt(startDate.substring(4, 6)),
            Integer.parseInt(startDate.substring(6, 8)));
    LocalDate toDate = LocalDate.of(
            Integer.parseInt(endDate.substring(0, 4)),
            Integer.parseInt(endDate.substring(4, 6)),
            Integer.parseInt(endDate.substring(6, 8)));
    LocalDate randomDate = fromDate.plusDays(ThreadLocalRandom.current().nextLong(fromDate.until(toDate, ChronoUnit.DAYS) + 1));
    return randomDate;
}

 

 

*개선한 버전

/**
 * getRandomDate
 * 
 * @param String(yyyyMMdd)
 * @param String(yyyyMMdd)
 * @return LocalDate(yyyy-MM-dd)
 */
public LocalDate getRandomDate(String startDate, String endDate) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

    LocalDate fromDate = LocalDate.parse(startDate, formatter);
    LocalDate toDate = LocalDate.parse(endDate, formatter);

    long daysBetween = fromDate.until(toDate, ChronoUnit.DAYS) + 1;
    LocalDate randomDate = fromDate.plusDays(ThreadLocalRandom.current().nextLong(daysBetween));

    return randomDate;
}

 

 

728x90
728x90

댓글