JAVA/포스팅

java.time.YearMonth 클래스

짜집퍼박사(짜박) 2023. 11. 17. 15:05

java.time.YearMonth 클래스는 연도와 월을 함께 표현하는 클래스로, java.time 패키지에서 제공됩니다. 이 클래스는 연도와 월을 효과적으로 다루기 위한 메서드를 제공합니다.

 

1. YearMonth 클래스의 생성

YearMonth 객체는 다양한 방법으로 생성할 수 있습니다.

 

정적 팩토리 메서드 이용

YearMonth yearMonth = YearMonth.of(2023, 11); // 2023년 11월

현재 연도와 월 가져오기

YearMonth currentYearMonth = YearMonth.now();

YearMonth 사용 예제

import java.time.YearMonth;

public class YearMonthExample {
    public static void main(String[] args) {
        // 정적 팩토리 메서드를 사용하여 YearMonth 객체 생성
        YearMonth yearMonth = YearMonth.of(2023, 11); // 2023년 11월

        // 현재 연도와 월 가져오기
        YearMonth currentYearMonth = YearMonth.now();

        // 출력
        System.out.println("YearMonth: " + yearMonth);
        System.out.println("Current YearMonth: " + currentYearMonth);
    }
}

이 예제에서는 YearMonth 클래스를 사용하여 특정 연도와 월, 현재 연도와 월을 생성하고 출력하는 간단한 예제를 보여줍니다.

 

2. YearMonth 메서드

YearMonth 클래스에는 다양한 메서드가 있습니다. 몇 가지 주요 메서드는 다음과 같습니다.

- getYear(): 해당 YearMonth의 연도를 반환합니다.
- getMonthValue(): 해당 YearMonth의 월을 반환합니다.
- isLeapYear(): 해당 연도가 윤년인지 여부를 확인합니다.
- plusMonths(long monthsToAdd): 특정 월을 더한 새로운 YearMonth 객체를 생성합니다.
- minusMonths(long monthsToSubtract): 특정 월을 뺀 새로운 YearMonth 객체를 생성합니다.

 

YearMonth 메서드 사용 예제

import java.time.YearMonth;

public class YearMonthMethodsExample {
    public static void main(String[] args) {
        // YearMonth 객체 생성
        YearMonth yearMonth = YearMonth.of(2023, 11); // 2023년 11월

        // YearMonth의 메서드 사용
        System.out.println("Year: " + yearMonth.getYear());         // 2023
        System.out.println("Month: " + yearMonth.getMonthValue());  // 11
        System.out.println("Is Leap Year: " + yearMonth.isLeapYear());  // false

        // 특정 월을 더하고 빼기
        YearMonth futureYearMonth = yearMonth.plusMonths(5);
        YearMonth pastYearMonth = yearMonth.minusMonths(2);

        System.out.println("YearMonth in the Future: " + futureYearMonth);
        System.out.println("YearMonth in the Past: " + pastYearMonth);
    }
}

이 예제에서는 YearMonth 객체를 생성하고, getYear() 및 getMonthValue() 메서드로 연도와 월 값을 가져오고, isLeapYear() 메서드로 윤년 여부를 확인합니다. 또한, plusMonths()와 minusMonths() 메서드를 사용하여 특정 월을 더하고 빼는 예제를 보여줍니다.

 

With ChatGPT

'JAVA > 포스팅' 카테고리의 다른 글

java.time 패키지의 Temporal 인터페이스  (0) 2023.11.17
java.time.Clock 클래스  (0) 2023.11.17
java.time.Year 클래스  (0) 2023.11.17
java.time.MonthDay 클래스  (0) 2023.11.17
java.time.Month 클래스  (0) 2023.11.17