#12장 새로운 날짜와 시간 API
Raoul-Gabriel Urma 저, 우정은 역 「Modern Java in Action, 2019」를 읽고 정리하였습니다.
이 장의 내용
자바8에서 새로운 날짜와 시간 라이브러리를 제공하는 이유 사람이나 기계가 이해 해할 수 있는 날짜와 시간 표현 방법
시간의 양 정의하기
날짜 조작, 포매팅, 파싱
시간대와 캘린더 다루기
12.1 LocalDate, LocalTime, LocalDateTime, Instant, Duration, and Period
java.time 패키지
간단한 dates and intervals 먼저 살펴보자.
LocalDate and LocalTime
getDayOfMonth() 랑 getDayOfWeek()는 어떻게 나올까?
LocalDate date = LocalDate.of(2017, 9, 21); // 2017-09-21 또는
// LocalDate today = LocalDate.now();
int year = date.getYear(); // 2017
Month month = date.getMonth(); // SEPTEMBER
int day = date.getDayOfMonth(); // 퀴즈: 머가 나올까?
DayOfWeek dow = date.getDayOfWeek(); // 퀴즈: 머가 나올까?
int len = date.lengthOfMonth(); // 30
boolean leap = date.isLeapYear(); // false
// 위 퀴즈 답은 각각 21, THURSDAY
// get에게 TemporalField를 넘겨서 temporal 객체의 특정 필드를 가져올 수 있다.
int year = date.get(ChronoField.YEAR);
int month = date.get(ChronoField.MONTH_OF_YEAR);
int day = date.get(ChronoField.DAY_OF_MONTH);
// 이렇게 가독성 높게 바꿔도 된다
int year = date.getYear();
int month = date.getMonthValue();
int day = date.getDayOfMonth();
LocalTime time = LocalTime.of(13, 45, 20); // 13:45:20
int hour = time.getHour();
int minute = time.getMinute();
int second = time.getSecond();
// 스트링 사용시
LocalDate date = LocalDate.parse("2017-09-21");
LocalTime time = LocalTime.parse("13:45:20");Combining a date and a time
LocalDateTime : Date + Time
Instant: a date and time for machines
LocalDateTime과 Instant 목적은 다르다. Instant는 기계를 위해서만 사용.
Defining a Duration or a Period
두 시점 사이의 시간
12.2 Manipulating, parsing, and formatting dates
퀴즈
date는 무엇이 나올까?
TemporalAdjusters
적절한 TemporalAdjusters의 메소드를 찾을 수 없다면, 아래 인터페이스 상속하여 직접 구현한다.
퀴즈
오늘 이후로 일해야 되는 다음 날짜를 구해라. (토요일, 일요일 빼기)
정답
날짜와 시간 객체 출력과 파싱
formatting과 parsing: 날짜와 시간 관련 작업에서 필수
DateTimeFormatter 클래스: 날짜나 시간을 특정 형식의 문자열로 만들 수 있다.
java.util.DateFormat 클래스와 달리 스레드 세이프하다.
12.3 다양한 시간대와 캘린더 활용 방법
새로운 날짜와 시간 API을 사용하면, 다양한 시간대를 간단하게 처리할 수 있다.
시간대 사용하기
ZoneRules클래스에는 40개 정도의 시간대가 있다.

UTC/Greenwich 기준의 고정 오프셋
UTC 기준으로 시간대 표현하는 법
대안 캘린더 시스템 사용하기
ThaiBuddhistDate, MinguoDate, OapaneseDate, HijrahDate
이슬람력
가장 복잡하다.
Last updated