java.time.MonthDay 클래스는 월과 일을 나타내는 클래스로, java.time 패키지에서 제공됩니다. 이 클래스는 특정 연도와 연결되지 않은 월과 일만을 나타냅니다. 따라서 연도 정보 없이 월과 일 정보만을 다루기 위해 사용됩니다.
1. MonthDay 클래스의 생성
MonthDay 객체는 다양한 방법으로 생성할 수 있습니다.
정적 팩토리 메서드 이용
MonthDay monthDay = MonthDay.of(Month.FEBRUARY, 14);
현재 날짜를 이용
MonthDay currentMonthDay = MonthDay.now();
MonthDay 사용 예제
import java.time.Month;
import java.time.MonthDay;
import java.time.LocalDate;
public class MonthDayExample {
public static void main(String[] args) {
// 정적 팩토리 메서드를 사용하여 MonthDay 생성
MonthDay february14 = MonthDay.of(Month.FEBRUARY, 14);
// 현재 날짜를 가져오기
LocalDate currentDate = LocalDate.now();
// 현재 날짜의 월과 일 정보만을 사용하여 MonthDay 생성
MonthDay currentMonthDay = MonthDay.from(currentDate);
// 출력
System.out.println("February 14: " + february14);
System.out.println("Current MonthDay: " + currentMonthDay);
}
}
이 예제에서는 MonthDay 클래스를 생성하고 출력하는 간단한 예제를 보여줍니다.
2. MonthDay 메서드
MonthDay 클래스에는 다양한 메서드가 있습니다. 몇 가지 주요 메서드는 다음과 같습니다.
- getMonthValue(): 해당 MonthDay의 월을 반환합니다.
- getDayOfMonth(): 해당 MonthDay의 일을 반환합니다.
- atYear(int year): 특정 연도에 대한 LocalDate를 생성합니다.
MonthDay 메서드 사용 예제
import java.time.Month;
import java.time.MonthDay;
import java.time.LocalDate;
public class MonthDayMethodsExample {
public static void main(String[] args) {
// MonthDay 객체 생성
MonthDay february14 = MonthDay.of(Month.FEBRUARY, 14);
// MonthDay의 메서드 사용
System.out.println("Month: " + february14.getMonthValue()); // 2
System.out.println("Day: " + february14.getDayOfMonth()); // 14
// 특정 연도에 대한 LocalDate 생성
LocalDate dateWithYear = february14.atYear(2023);
System.out.println("Date with Year: " + dateWithYear);
}
}
이 예제에서는 MonthDay 객체를 생성하고, getMonthValue()와 getDayOfMonth() 메서드를 사용하여 월과 일을 출력하고, atYear() 메서드를 사용하여 특정 연도에 대한 LocalDate를 생성합니다.
With ChatGPT
'JAVA > 포스팅' 카테고리의 다른 글
java.time.YearMonth 클래스 (0) | 2023.11.17 |
---|---|
java.time.Year 클래스 (0) | 2023.11.17 |
java.time.Month 클래스 (0) | 2023.11.17 |
자바 java.time DayOfWeek (0) | 2023.11.17 |
DateTimeFormatter 클래스 (0) | 2023.11.17 |