[java] 자바 11에서 추가된 FormatStyle을 활용한 날짜 형식 지정
자바 11에서는 새로운 FormatStyle
클래스가 도입되어 날짜 및 시간의 형식을 지정할 수 있게 되었습니다. 이를 통해 코드를 더 간결하고 가독성 높게 작성할 수 있습니다.
FormatStyle 소개
FormatStyle
은 java.time.format
패키지에 포함되어 있으며, 날짜 및 시간 객체를 원하는 형식으로 출력하기 위해 사용됩니다. 현재는 세 가지 스타일을 제공합니다.
SHORT
: 년-월-일 (예: 2022-01-01)MEDIUM
: 월-일-년 (예: 01-01-2022)LONG
: 월 일, 년 (예: 1월 1일, 2022)
이러한 스타일을 사용하여 원하는 형식으로 날짜를 포맷할 수 있습니다.
사용 방법
FormatStyle
을 사용하기 위해 먼저 DateTimeFormatter
객체를 생성해야 합니다. 아래는 FormatStyle
을 활용한 예제 코드입니다.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
public class DateFormattingExample {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
// SHORT 스타일로 날짜 포맷팅
DateTimeFormatter shortFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
String shortFormattedDate = currentDate.format(shortFormatter);
System.out.println("SHORT 스타일 : " + shortFormattedDate);
// MEDIUM 스타일로 날짜 포맷팅
DateTimeFormatter mediumFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
String mediumFormattedDate = currentDate.format(mediumFormatter);
System.out.println("MEDIUM 스타일 : " + mediumFormattedDate);
// LONG 스타일로 날짜 포맷팅
DateTimeFormatter longFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
String longFormattedDate = currentDate.format(longFormatter);
System.out.println("LONG 스타일 : " + longFormattedDate);
}
}
위 예제 코드는 현재 날짜를 LocalDate.now()
로 가져온 후, DateTimeFormatter
객체를 생성하여 ofLocalizedDate()
메소드에 FormatStyle
을 지정합니다. 그 다음 format()
메소드를 사용하여 LocalDate
객체를 원하는 형식으로 포맷팅합니다.
결과
실행 결과는 다음과 같습니다.
SHORT 스타일 : 2022-01-01
MEDIUM 스타일 : 01-01-2022
LONG 스타일 : 1월 1일, 2022
결론
자바 11의 FormatStyle
을 활용하여 날짜 형식을 지정하는 것은 매우 편리하고 간단한 방법입니다. 이를 통해 코드의 가독성을 높이고, 원하는 형식으로 날짜를 포맷할 수 있습니다. 추가로 FormatStyle
외에도 FormatStyle.FULL
이나 사용자 정의 패턴을 사용하여 더 다양한 형식을 지정할 수 있습니다. 자세한 내용은 Java 공식 문서를 참조하시기 바랍니다.