[Java] Class DateTimeFormatter

by 민갤

Java /

package java.time

Date와 Calendar가 가지고 있던 단점들을 개선한 패키지.

4개의 하위 패키지를 가지고 있다.

날짜나 시간을 변경하는 메서드들은 항상 변경된 새로운 객체를 반환한다. = 불변Immutable

Class DateTimeFormatter

java.time.format 패키지의 형식화(formatting)와 관련된 클래스들 중 핵심인 클래스.

자주 쓰이는 다양한 형식들을 정의하고 있다.

그 외의 형식이 필요할 경우 직접 정의해서 사용할 수 있다.

format()

날짜와 시간의 형식화에 사용된다.

DateTimeFormatter뿐 아니라 LocalDate나 LocalTime 같은 클래스에도 있다.

LocalDate date = LocalDate.now();
System.out.println(DateTimeFormatter.ISO_LOCAL_DATE.format(date));   // 2017-09-16
System.out.println(date.format(DateTimeFormatter.ISO_LOCAL_DATE));   // 2017-09-16

상수로 정의된 형식들

형식설명형식설명
  ISO_DATE_TIME  Date and time with Zoneld  ISO_INSTANT  Date and Time of an Instant
  ISO_LOCAL_DATE  ISO Local Date  BASIC_ISO_DATE  Basic ISO date
  ISO_LOCAL_TIME  time without offset  ISO_DATE  ISO Date with or without offset
  ISO_LOCAL_DATE_TIME  ISO Local Date and Time  ISO_TIME  Time with of without offset
  ISO_OFFSET_DATE  ISO Date with Offset  ISO_ORDINAL_DATE  Year and day of year
  ISO_OFFSET_TIME  Time with offset  ISO_WEEK_DATE  Year and Week
  ISO_OFFSET_DATE_TIME  Date Time with Offset  RFC_1123_DATE_TIME  RFC 1123 / RFC 822
  ISO_ZONED_DATE_TIME  Zoned Date Time
public class Test {
    public static void main(String[] args){

        LocalDate date = LocalDate.now();      
        LocalTime time = LocalTime.now(); 
        LocalDateTime dt = LocalDateTime.now();
        ZonedDateTime zdt = ZonedDateTime.now();
        OffsetDateTime odt = zdt.toOffsetDateTime();
        Instant in = Instant.now();
        
        print(dt.format(DateTimeFormatter.ISO_DATE_TIME));              // 2017-09-16T23:05:08.4
        print(date.format(DateTimeFormatter.ISO_LOCAL_DATE));           // 2017-09-16
        print(time.format(DateTimeFormatter.ISO_LOCAL_TIME));           // 23:05:08.4
        print(dt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));        // 2017-09-16T23:05:08.4
        print(odt.format(DateTimeFormatter.ISO_OFFSET_DATE));           // 2017-09-16+09:00
        print(odt.format(DateTimeFormatter.ISO_OFFSET_TIME));           // 23:05:08.402+09:00
        print(odt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));      // 2017-09-16T23:05:08.402+09:00
        print(zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));       // 2017-09-16T23:05:08.402+09:00[Asia/Seoul]
        print(zdt.format(DateTimeFormatter.ISO_INSTANT));               // 2017-09-16T14:05:08.402Z
        print(date.format(DateTimeFormatter.BASIC_ISO_DATE));           // 20170916
        print(date.format(DateTimeFormatter.ISO_DATE));                 // 2017-09-16
        print(time.format(DateTimeFormatter.ISO_TIME));                 // 23:05:08.4
        print(date.format(DateTimeFormatter.ISO_ORDINAL_DATE));         // 2017-259
        print(date.format(DateTimeFormatter.ISO_WEEK_DATE));            // 2017-W37-6
        print(odt.format(DateTimeFormatter.RFC_1123_DATE_TIME));        // Sat, 16 Sep 2017 23:05:08 +0900
        
    }

    public static void print(Object obj){ System.out.println(obj); }
}

Locale에 종속된 형식화

static 메서드인 ofLocalizedDate(), ofLocalizedTime(), ofLocalizedDateTime()은 로케일에 종속적인 포맷터를 생성한다.

DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
System.out.println(dtf.format(LocalDate.now()));    // 17. 9. 16
  • FormatStyle 종류에 따른 출력 형태
FormatStyle날짜시간
FULL2017년 6월 12일 월요일N/A
LONG2017년 6월 12일 (월) 오후 3시 20분 30초
MEDIUM2017. 6. 12오후 3:20:30
SHORT12. 6. 12오후 3:20

ofPattern()

출력 형식을 직접 정의할 수 있다.

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
  • G  연대 (BC, AD)
  • y/Y  년도
  • M/L  월 (1~12 또는 1월~12월)
  • Q/q  분기(quarter)
  • w  년의 몇 번째 주 (1~53)
  • W  월의 몇 번째 주 (1~5)
  •  년의 몇 번째 일 (1~366)
  •  월의 몇 번째 일 (1~31)
  •  월의 몇 번째 요일 (1~5)
  • E/e   요일
  • a  오전/오후 (AM/PM)
  • H  시간 (0~23)
  • h  시간 (1~12)
  • k  시간 (1~24)
  • K  시간 (0~11)
  • m  분 (0~59)
  • s  초 (0~59)
  • S  1/1000초 (0~999)
  • A  1/1000초 (그 날의 0시 0분 0초 부터의 시간)
  • n  나노초 (0~999999999)
  • N  나노초 (그 날의 0시 0분 0초 부터의 시간)
  • V  시간대 ID(VV)
  • z  시간대(Time zone) 이름
  • O  지역화된 zone-offset
  • Z  zone-offset
  • X/x  zone-offset(Z는 +00:00를 의미)
  •  escape 문자 (특수문자를 표현하는 데 사용)
String[] pattern = {"G",     // 서기
                    "y",     // 2017
                    "M",     // 9
                    "q",     // 3
                    "w",     // 37
                    "W",     // 3
                    "D",     // 259
                    "d",     // 16
                    "F",     // 2
	            "e",     // 7
                    "a",     // 오후
                    "H",     // 23
                    "h",     // 11
                    "k",     // 23
                    "K",     // 11
                    "m",     // 9
                    "s",     // 18
                    "S",     // 9
                    "A",     // 83358977
                    "n",     // 977000000
                    "N",     // 83358977000000
                    "z",     // KST
                    "O",     // GMT+9
                    "Z",     // +0900
                    "x" };   // +09


for(int i = 0; i < pattern.length; i++) {
	DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern[i]);
	System.out.println(zdt.format(dtf));
}

parse()

문자열을 날짜/시간으로 파싱(parsing. 해석)한다.

static LocalDateTime parse(CharSequence text);
static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter);
  • DateTimeFormatter에 상수로 정의된 형식을 사용할 때
LocalDate date = LocalDate.parse("2017-06-06", DateTimeFormatter.ISO_LOCAL_DATE);
  • 자주 사용되는 기본적인 형식의 문자열을 파싱할 경우

    ISO_LOCAL_DATE와 같은 형식화 상수를 사용하지 않고도 파싱할 수 있다.

LocalDate date = LocalDate.parse("2017-11-17");
LocalTime time = LocalTime.parse("17:11:17");
LocalDateTime dt = LocalDateTime.parse("2017-11-17T12:34:56");
  • ofPattern()을 이용하여 파싱
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime day = LocalDateTime.parse("2015-11-17 21:59:58", pattern);

DateTimeFormatter API

참고 서적: 자바의 정석 3판 2

Author

민갤

민갤

Back-End Developer

꾸잉꾸잉하고 웁니다.

로그인

디코에 오신 것을 환영해요!
전문가들의 수많은 아티클 창고 🤓