티스토리 뷰

728x90

작성하다가 보니 시간 변경과 비교하는걸 안 한 거 같아서 여기에 다시 작성함.

시간을 더하거나 빼는 것은 1편에서 plus** 또는 minus** 로 할 수 있음.

시간을 변경할 때는 with**  메서드로 변경할 수 있다.

시간 변경

출처 - 이것이 자바다

private static void modifyDate() {
    LocalTime localTime = LocalTime.of(1, 15, 30)
            .withHour(1)    //시간 변경
            .withMinute(10) //분 변경
            .withSecond(25) //초 변경
            .withNano(100); //나노초 변경
    System.out.println("localTime = " + localTime);

    LocalDate localDate = LocalDate.of(2021, 3, 25)
            .withYear(2020) //년 변경
            .withMonth(12)  //월 변경
            .withDayOfMonth(25) //월의 일 변경
            .withDayOfYear(11)  //년의 일 변경
            .with(TemporalAdjusters.firstDayOfMonth()); //상대 변경
    System.out.println("localDate = " + localDate);
}

여기서 with() 메서드는 상대 변경이라고 되어있는데 이것은 현재 날짜를 기준으로 해의 첫 번째 일 또는 마지막 일, 달의 첫 번째 일 또는 마지막 일 등 상대적인 날짜를 리턴한다. 파라미터 값은 TemporalAdjuster 타입으로  TemporalAdjusters 클래스에 구현된 정적 메서드를 호출하면 된다.

출처 - 이것이 자바다

예제를 보고 날짜랑 같이 보면 이해가 된다.

public class DateTimeChangeExample {
    public static void main(String[] args) {

        LocalDateTime now = LocalDateTime.now();
        System.out.println("현재 = " + now);

        //직접 변경
        LocalDateTime targetDateTime = null;
        targetDateTime = now
                .withYear(2024)
                .withMonth(10)
                .withDayOfMonth(5)
                .withHour(13)
                .withMinute(30)
                .withSecond(20);
        System.out.println("직접변경 = " + targetDateTime);

        //년도 상대 변경
        targetDateTime = now.with(TemporalAdjusters.firstDayOfYear());
        System.out.println("이번 해의 첫 일 = " + targetDateTime);
        targetDateTime = now.with(TemporalAdjusters.lastDayOfYear());
        System.out.println("이번 해의 마지막 일 = " + targetDateTime);
        targetDateTime = now.with(TemporalAdjusters.firstDayOfNextYear());
        System.out.println("다음 해의 첫 일 = " + targetDateTime);

        //월 상대 변경
        targetDateTime = now.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("이번 달의 첫 일 = " + targetDateTime);
        targetDateTime = now.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("이번 달의 마지막 일 = " + targetDateTime);
        targetDateTime = now.with(TemporalAdjusters.firstDayOfNextMonth());
        System.out.println("다음 달의 첫 일 = " + targetDateTime);

        //요일 상대 변경
        targetDateTime = now.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
        System.out.println("이번 달의 첫 월요일 = " + targetDateTime);
        targetDateTime = now.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
        System.out.println("돌아오는 월요일 = " + targetDateTime);
        targetDateTime = now.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
        System.out.println("지난 월요일 = " + targetDateTime);
    }
}

//결과
현재 = 2021-03-29T15:07:42.957290
직접변경 = 2024-10-05T13:30:20.957290
이번 해의 첫 일 = 2021-01-01T15:07:42.957290
이번 해의 마지막 일 = 2021-12-31T15:07:42.957290
다음 해의 첫 일 = 2022-01-01T15:07:42.957290
이번 달의 첫 일 = 2021-03-01T15:07:42.957290
이번 달의 마지막 일 = 2021-03-31T15:07:42.957290
다음 달의 첫 일 = 2021-04-01T15:07:42.957290
이번 달의 첫 월요일 = 2021-03-01T15:07:42.957290
돌아오는 월요일 = 2021-04-05T15:07:42.957290
지난 월요일 = 2021-03-22T15:07:42.957290

 

TemporalAdjuster 직접 구현하기

TemporalAdjuster에 정의된 메서드를 제외하고 필요하면 자주 사용되는 날짜를 계산해주는 메서드를 직접 만들 수 도 있다.

with의 메서드 파라미터는 TemporalAdjuster 인터페이스를 파라미터로 받게 되는데 바로 이 TemporalAdjuster 인터페이스를 직접 구현해서 메서드의 파라미터로 넣어주면 된다.

default Temporal with(TemporalAdjuster adjuster) {
    return adjuster.adjustInto(this);
}

with()는 LocalTime, LocalDateTime, ZonedDateTime, Instant 등 대부분의 날짜와 시간에 관련된 클래스에 포함되어 있다.

그렇다면 TemporalAdjuster 인터페이스를 살펴보면 아래와 같이 되어있다.

@FunctionalInterface
public interface TemporalAdjuster {
    Temporal adjustInto(Temporal temporal);
}

@FunctionalInterface 애노테이션이 붙은 추상메서드가 단 하나인 인터페이스이다.

그럼 람다를 활용해서 메서드의 파라미터로 값을 넘길 수가 있다. 혹은 TemporalAdjuster 인터페이스를 구현한 클래스를 만들어주면 된다.

TemporalAdjuster 인터페이스를 구현한 클래스 만들기

public class CustomDayAfterTomorrow implements TemporalAdjuster {
    @Override
    public Temporal adjustInto(Temporal temporal) {
        return temporal.plus(2, ChronoUnit.DAYS);
    }
}

날짜의 2일을 더하는 커스텀한 날짜 계산 클래스를 구현했다.

사용법

//TemporalAdjuster직접 구현하기
targetDateTime = now.with(new CustomDayAfterTomorrow());
System.out.println("TemporalAdjuster 직접 구현 = " + targetDateTime);

 

람다로 사용하는 방법

//람다
targetDateTime = now.with(temporal -> temporal.plus(2, ChronoUnit.DAYS));
System.out.println("TemporalAdjuster 람다 = " + targetDateTime);

 

시간 비교

isBefore() 메서드와 isEqual()과 isAfter() 메서드를 사용하면 된다. 

여기서 isAfter() 메서드는 LocalDate에서만 가능하다.

예제는 LocalDate 만 구현했지만 LocalTime과 LocalDateTime으로도 사용할 수 있다.

private static void compareDate() {
    LocalDate startDate = LocalDate.of(2021, 3, 25);
    LocalDate endDate = LocalDate.of(2021, 4, 25);

    //startDate가 endDate보다 이전인지 비교
    startDate.isBefore(endDate);
    //startDate가 endDate와 같은지 비교
    startDate.isEqual(endDate);
    //startDate가 endDate보다 이후인지 비교
    startDate.isAfter(endDate);
}

참고

이것이 자바다 www.yes24.com/Product/Goods/15651484?OzSrank=2

자바의 정석 www.yes24.com/Product/Goods/24259565?OzSrank=2

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함