소개
Java 8 의 LocalDate 클래스는 날짜 값을 조작하기 위한 여러 메서드를 제공합니다. 그 중 하나인 withMonth() 메서드는 연중 월을 변경하거나 설정한 후 새로운 LocalDate 인스턴스를 반환합니다.
Java 8 의 LocalDate 클래스는 날짜 값을 조작하기 위한 여러 메서드를 제공합니다. 그 중 하나인 withMonth() 메서드는 연중 월을 변경하거나 설정한 후 새로운 LocalDate 인스턴스를 반환합니다.
첫 번째 단계는 Java 에서 LocalDate 인스턴스를 생성하는 것입니다. LocalDate 클래스는 java.time 패키지에 있으므로 코드 파일의 시작 부분에 패키지를 포함합니다. LocalDate 클래스는 새로운 LocalDate 인스턴스를 생성할 수 있는 of() 메서드를 제공합니다.
import java.time.LocalDate;
public class LocalDateWithMonthMethodExample {
public static void main(String[] args) {
// creating a new LocalDate instance
LocalDate date = LocalDate.of(2022, 10, 12);
// printing the original date
System.out.println("Original Date: " + date);
}
}
터미널에서 다음 명령을 사용하여 코드를 컴파일하고 실행합니다.
javac LocalDateWithMonthMethodExample.java && java LocalDateWithMonthMethodExample
withMonth() 메서드는 연중 월을 인수로 제공된 값으로 설정한 새로운 LocalDate 인스턴스를 반환합니다.
withMonth() 메서드를 사용하여 다른 연중 월을 설정하고 새로 생성된 날짜를 얻을 수 있습니다. 여기서는 연중 월을 4 로 설정하고 새 날짜를 얻습니다.
// setting the month-of-year to 4 and getting the new date
LocalDate newDate = date.withMonth(4);
// printing the new date
System.out.println("New Date: " + newDate);
전체 코드는 다음과 같습니다.
import java.time.LocalDate;
public class LocalDateWithMonthMethodExample {
public static void main(String[] args) {
// creating a new LocalDate instance
LocalDate date = LocalDate.of(2022, 10, 12);
// printing the original date
System.out.println("Original Date: " + date);
// setting the month-of-year to 4 and getting the new date
LocalDate newDate = date.withMonth(4);
// printing the new date
System.out.println("New Date: " + newDate);
}
}
터미널에서 다음 명령을 사용하여 코드를 컴파일하고 실행합니다.
javac LocalDateWithMonthMethodExample.java && java LocalDateWithMonthMethodExample
다음과 같은 출력을 볼 수 있습니다.
Original Date: 2022-10-12
New Date: 2022-04-12
withMonth() 메서드에 전달된 월 값이 유효하지 않은 경우, 즉 [1, 12] 범위를 벗어나는 경우 DateTimeException을 발생시킵니다.
다음은 유효하지 않은 월 값을 처리하는 방법을 보여주는 예제입니다.
import java.time.DateTimeException;
import java.time.LocalDate;
public class LocalDateWithMonthMethodExample {
public static void main(String[] args) {
// creating a new LocalDate instance
LocalDate date = LocalDate.of(2022, 10, 12);
// printing the original date
System.out.println("Original Date: " + date);
try {
// trying to set an invalid month value (13)
LocalDate newDate = date.withMonth(13);
// printing the new date
System.out.println("New Date: " + newDate);
} catch(DateTimeException ex) {
System.out.println("Invalid month value provided: " + ex.getMessage());
}
}
}
터미널에서 다음 명령을 사용하여 코드를 컴파일하고 실행합니다.
javac LocalDateWithMonthMethodExample.java && java LocalDateWithMonthMethodExample
다음과 같은 출력을 볼 수 있습니다.
Original Date: 2022-10-12
Invalid month value provided: Invalid value for MonthOfYear (valid values 1 - 12): 13
withMonth() 메서드는 연중 월 값이 새 값으로 설정된 새로운 LocalDate 인스턴스를 반환하며, 원래 날짜 인스턴스를 변경하지 않습니다. 원래 날짜에서 연중 월 값을 변경하려면 withMonth()에서 반환된 값을 원래 날짜 인스턴스에 다시 할당해야 합니다. 다음과 같습니다.
// changing the month-of-year in the original date instance
date = date.withMonth(11);
// printing the updated date
System.out.println("Updated Date: " + date);
전체 코드는 다음과 같습니다.
import java.time.LocalDate;
public class LocalDateWithMonthMethodExample {
public static void main(String[] args) {
// creating a new LocalDate instance
LocalDate date = LocalDate.of(2022, 10, 12);
// printing the original date
System.out.println("Original Date: " + date);
// setting the month-of-year to 5 and getting the new date
LocalDate newDate = date.withMonth(5);
// printing the new date
System.out.println("New Date: " + newDate);
// changing the month-of-year in the original date instance
date = date.withMonth(11);
// printing the updated date
System.out.println("Updated Date: " + date);
}
}
터미널에서 다음 명령을 사용하여 코드를 컴파일하고 실행합니다.
javac LocalDateWithMonthMethodExample.java && java LocalDateWithMonthMethodExample
다음과 같은 출력을 볼 수 있습니다.
Original Date: 2022-10-12
New Date: 2022-05-12
Updated Date: 2022-11-12
월을 변경할 때 월의 날짜가 해당 연도에 유효하지 않은 경우, 새 월의 마지막 유효한 날짜로 변경됩니다. 예를 들어, 윤년에서 연중 월을 2 월에서 4 월로 변경하면, 일 값은 자동으로 4 월의 마지막 유효한 날짜로 조정됩니다.
// creating a new LocalDate instance
LocalDate date = LocalDate.of(2024, 2, 29);
// printing the original date
System.out.println("Original Date: " + date);
// setting the month-of-year to April
LocalDate newDate = date.withMonth(4);
// printing the new date
System.out.println("New Date: " + newDate);
전체 코드는 다음과 같습니다.
import java.time.LocalDate;
public class LocalDateWithMonthMethodExample {
public static void main(String[] args) {
// creating a new LocalDate instance
LocalDate date = LocalDate.of(2024, 2, 29);
// printing the original date
System.out.println("Original Date: " + date);
// setting the month-of-year to April
LocalDate newDate = date.withMonth(4);
// printing the new date
System.out.println("New Date: " + newDate);
}
}
터미널에서 다음 명령을 사용하여 코드를 컴파일하고 실행합니다.
javac LocalDateWithMonthMethodExample.java && java LocalDateWithMonthMethodExample
다음과 같은 출력을 볼 수 있습니다.
Original Date: 2024-02-29
New Date: 2024-04-30
withMonth() 메서드를 루프에서 사용하여 서로 다른 연중 월 값을 가진 날짜 목록을 생성할 수 있습니다. 다음은 2022 년의 각 달에 대한 날짜를 생성하는 예시입니다.
// generating dates for each month of the year 2022
for (int month = 1; month <= 12; month++) {
LocalDate date = LocalDate.of(2022, month, 1);
System.out.println("Date for " + date.getMonth() + ": " + date);
}
전체 코드는 다음과 같습니다.
import java.time.LocalDate;
public class LocalDateWithMonthMethodExample {
public static void main(String[] args) {
// generating dates for each month of the year 2022
for (int month = 1; month <= 12; month++) {
LocalDate date = LocalDate.of(2022, month, 1);
System.out.println("Date for " + date.getMonth() + ": " + date);
}
}
}
터미널에서 다음 명령을 사용하여 코드를 컴파일하고 실행합니다.
javac LocalDateWithMonthMethodExample.java && java LocalDateWithMonthMethodExample
다음과 같은 출력을 볼 수 있습니다.
Date for JANUARY: 2022-01-01
Date for FEBRUARY: 2022-02-01
Date for MARCH: 2022-03-01
Date for APRIL: 2022-04-01
Date for MAY: 2022-05-01
Date for JUNE: 2022-06-01
Date for JULY: 2022-07-01
Date for AUGUST: 2022-08-01
Date for SEPTEMBER: 2022-09-01
Date for OCTOBER: 2022-10-01
Date for NOVEMBER: 2022-11-01
Date for DECEMBER: 2022-12-01
getMonthValue() 메서드는 날짜의 연중 월 값을 가져오는 데 사용됩니다. 다음은 withMonth() 및 getMonthValue() 메서드를 사용하여 날짜의 연중 월 값을 변경하고 가져오는 방법을 보여주는 예시입니다.
// creating a new LocalDate instance
LocalDate date = LocalDate.of(2022, 11, 15);
// printing the original date
System.out.println("Original Date: " + date);
// getting the month-of-year value
int originalMonthValue = date.getMonthValue();
// changing the month-of-year to 10
date = date.withMonth(10);
// getting the new month-of-year value
int newMonthValue = date.getMonthValue();
// printing the updated date and month values
System.out.println("Updated Date: " + date);
System.out.println("Original Month Value: " + originalMonthValue);
System.out.println("New Month Value: " + newMonthValue);
전체 코드는 다음과 같습니다.
import java.time.LocalDate;
public class LocalDateWithMonthMethodExample {
public static void main(String[] args) {
// creating a new LocalDate instance
LocalDate date = LocalDate.of(2022, 11, 15);
// printing the original date
System.out.println("Original Date: " + date);
// getting the month-of-year value
int originalMonthValue = date.getMonthValue();
// changing the month-of-year to 10
date = date.withMonth(10);
// getting the new month-of-year value
int newMonthValue = date.getMonthValue();
// printing the updated date and month values
System.out.println("Updated Date: " + date);
System.out.println("Original Month Value: " + originalMonthValue);
System.out.println("New Month Value: " + newMonthValue);
}
}
터미널에서 다음 명령을 사용하여 코드를 컴파일하고 실행합니다.
javac LocalDateWithMonthMethodExample.java && java LocalDateWithMonthMethodExample
다음과 같은 출력을 볼 수 있습니다.
Original Date: 2022-11-15
Updated Date: 2022-10-15
Original Month Value: 11
New Month Value: 10
이 랩에서는 withMonth() 메서드를 사용하여 연중 월이 새로운 값으로 설정된 LocalDate 인스턴스의 복사본을 만드는 방법을 배웠습니다. 또한 유효하지 않은 월 값을 처리하는 방법과 getMonthValue() 메서드를 사용하여 LocalDate 인스턴스의 연중 월 값을 가져오는 방법을 배웠습니다. withMonth() 메서드는 날짜를 조작하는 데 유용한 도구이며, 연도의 각 달에 대한 날짜 목록을 생성하는 것을 포함하여 다양한 방식으로 사용할 수 있습니다.