いつも調べてるのでメモっておく。
LocalDateクラスに標準で実装してくれればいいのにな。
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.time.LocalDate; import java.util.Objects; import org.junit.jupiter.api.Test; class LocalDateUtilsTest2 { static boolean between(LocalDate target, LocalDate from, LocalDate to) { if (Objects.isNull(target)) { throw new IllegalArgumentException("targetの値が指定されていません。"); } if (Objects.isNull(from)) { throw new IllegalArgumentException("fromの値が指定されていません。"); } if (Objects.isNull(to)) { throw new IllegalArgumentException("toの値が指定されていません。"); } if (target.isBefore(from)) { return false; } if (target.isAfter(to)) { return false; } return true; } @Test void target日付がnull() { try { between(null, LocalDate.now(), LocalDate.now()); fail(); } catch (IllegalArgumentException e) { } } @Test void from日付がnull() { try { between(LocalDate.now(), null, LocalDate.now()); fail(); } catch (IllegalArgumentException e) { } } @Test void to日付がnull() { try { between(LocalDate.now(), LocalDate.now(), null); fail(); } catch (IllegalArgumentException e) { } } @Test void 日付比較() { assertTrue(between(LocalDate.now(), LocalDate.now(), LocalDate.now())); assertFalse(between(LocalDate.of(2019, 12, 31), LocalDate.of(2020, 1, 1),LocalDate.of(2020, 1, 3))); assertTrue(between(LocalDate.of(2020, 1, 1), LocalDate.of(2020, 1, 1),LocalDate.of(2020, 1, 3))); assertTrue(between(LocalDate.of(2020, 1, 2), LocalDate.of(2020, 1, 1),LocalDate.of(2020, 1, 3))); assertTrue(between(LocalDate.of(2020, 1, 3), LocalDate.of(2020, 1, 1),LocalDate.of(2020, 1, 3))); assertFalse(between(LocalDate.of(2020, 1, 4), LocalDate.of(2020, 1, 1),LocalDate.of(2020, 1, 3))); } }