[java] 자바 11에서 추가된 YearMonth 클래스의 활용 방법

자바 11에서는 YearMonth 클래스가 추가되었습니다. 이 클래스는 연도와 월 정보를 담을 수 있는 유용한 기능을 제공합니다. 이번 글에서는 YearMonth 클래스의 활용 방법에 대해 알아보겠습니다.

1. YearMonth 객체 생성하기

YearMonth 객체를 생성하기 위해서는 YearMonth.of() 메서드를 사용합니다. 다음은 2021년 9월을 나타내는 YearMonth 객체를 생성하는 예제입니다.

YearMonth yearMonth = YearMonth.of(2021, 9);

2. YearMonth 정보 얻기

YearMonth 객체를 통해 연도와 월 정보를 얻을 수 있습니다. 아래는 YearMonth 객체로부터 연도와 월을 얻는 예제입니다.

int year = yearMonth.getYear();
int month = yearMonth.getMonthValue();

3. YearMonth 비교하기

YearMonth 객체끼리 비교하는 예제입니다. equals() 메서드를 사용하여 두 YearMonth 객체가 동일한 연도와 월을 가지는지 확인할 수 있습니다.

YearMonth otherYearMonth = YearMonth.of(2022, 3);

if (yearMonth.equals(otherYearMonth)) {
    System.out.println("같은 연도와 월을 가집니다.");
} else {
    System.out.println("다른 연도와 월을 가집니다.");
}

4. YearMonth 이동하기

YearMonth 객체를 특정 기간만큼 이동시킬 수 있습니다. plusYears(), plusMonths(), minusYears(), minusMonths() 메서드를 사용하여 YearMonth 객체를 이동시킬 수 있습니다.

YearMonth nextYearMonth = yearMonth.plusMonths(1);
YearMonth previousYearMonth = yearMonth.minusYears(1);

5. YearMonth 출력하기

YearMonth 객체를 원하는 형식으로 출력하는 예제입니다. DateTimeFormatter를 사용하여 출력 형식을 지정할 수 있습니다.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM");
String formattedYearMonth = yearMonth.format(formatter);

System.out.println("포맷된 YearMonth: " + formattedYearMonth);

결론

자바 11에서 추가된 YearMonth 클래스는 연도와 월 정보를 다룰 때 유용하게 사용할 수 있는 클래스입니다. 이 글에서는 YearMonth 클래스의 기본적인 활용 방법을 설명하였으니, 이를 참고하여 프로그래밍에 활용해보시기 바랍니다.

자세한 사항은 공식 자바 API 문서를 참고하시기 바랍니다.