JAVA/포스팅

DateTimeFormatter 클래스

짜집퍼박사(짜박) 2023. 11. 17. 13:32

DateTimeFormatter 클래스는 날짜와 시간 객체를 원하는 형식의 문자열로 포맷하거나, 문자열을 날짜와 시간 객체로 파싱하는 데 사용되는 클래스입니다. Java 8에서 java.time 패키지에서 도입되었습니다.'

 

1. DateTimeFormatter 객체 생성

미리 정의된 형식 사용

DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;

패턴을 사용하여 직접 형식 지정

DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

 

2. DateTimeFormatter를 사용하여 날짜와 시간 객체를 문자열로 변환

LocalDateTime now = LocalDateTime.now();
String formattedDateTime = formatter.format(now);
System.out.println(formattedDateTime);

 

3. 문자열을 DateTimeFormatter를 사용하여 날짜와 시간 객체로 변환

String dateString = "2022-10-31T12:30:45";
LocalDateTime parsedDateTime = LocalDateTime.parse(dateString, formatter);
System.out.println(parsedDateTime);

 

4. DateTimeFormatter 패턴 문자

- y : 연도
- M : 월
- d : 일
- H : 시간 (24시간 형식)
- h : 시간 (12시간 형식)
- m : 분
- s : 초
- E : 요일
등등...

 

5. DateTimeFormatter 패턴 문자 예제

DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
String formattedDateTime = customFormatter.format(now);
System.out.println(formattedDateTime); // 예: 2022-10-31 12:30:45

String dateString = "2022-10-31 12:30:45";
LocalDateTime parsedDateTime = LocalDateTime.parse(dateString, customFormatter);
System.out.println(parsedDateTime);

 

6. DateTimeFormatter의 withLocale 메서드

withLocale 메서드를 사용하여 지역화된 형식을 적용할 수 있습니다.

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
                                                .withLocale(Locale.US);

 

주의사항

- DateTimeFormatter는 스레드 안전(thread-safe)하므로 여러 스레드에서 안전하게 사용할 수 있습니다.
- DateTimeFormatter를 사용하면 날짜와 시간을 원하는 형식의 문자열로 쉽게 포맷할 수 있으며, 반대로 문자열을 날짜와 시간 객체로 파싱할 수 있습니다.

 

With ChatGPT

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

java.time.Month 클래스  (0) 2023.11.17
자바 java.time DayOfWeek  (0) 2023.11.17
java.time.Period 클래스  (0) 2023.11.17
java.time.Duration 클래스  (0) 2023.11.17
java.time.ZoneId 클래스  (0) 2023.11.17