[java] 자바 8 날짜와 시간 API에서 날짜 포맷 설정하기
자바 8에서는 java.time
패키지를 통해 새로운 날짜와 시간 API를 제공합니다. 이 API를 사용하여 날짜와 시간을 쉽게 다룰 수 있으며, 날짜 포맷 설정은 그 중 하나입니다.
DateTimeFormatter
클래스
DateTimeFormatter
클래스는 java.time.format.DateTimeFormatter
패키지에 포함되어 있으며, 날짜와 시간을 원하는 형식으로 포맷할 수 있도록 도와줍니다.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateFormatterExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = now.format(formatter);
System.out.println("포맷된 날짜와 시간: " + formattedDateTime);
}
}
위의 예제에서는 LocalDateTime
클래스를 사용하여 현재 날짜와 시간을 가져옵니다. 그리고 DateTimeFormatter
클래스를 사용하여 날짜와 시간의 포맷을 설정합니다. “yyyy-MM-dd HH:mm:ss”와 같은 패턴을 사용하여 원하는 포맷을 정의할 수 있습니다.
format()
메서드를 사용하여 LocalDateTime
인스턴스를 포맷된 문자열로 변환하고, 그 결과를 출력합니다.
위의 예제를 실행하면 다음과 같은 결과를 얻을 수 있습니다:
포맷된 날짜와 시간: 2022-01-01 12:34:56
이제 날짜와 시간을 원하는 포맷으로 설정할 수 있게 되었습니다.
참고
- Oracle Java Documentation
- Baeldung - Guide to the Java 8 DateTimeFormatter
- Java Tutorials - Format date and time