기록/JAVA
[JAVA8] Date 와 Time
jeongdalma
2021. 1. 14. 22:52
JAVA8에 새로운 날짜와 시간 API가 생긴 이유
그전까지 사용하던 java.util.Date클래스는 mutable하기 때문에 쓰레드에 안전하지 않다.
All about java.util.Date
This post is an attempt to reduce the number of times I need to explain things in Stack Overflow comments. You may well be reading it via a link from Stack Overflow – I intend to refer to thi…
codeblog.jonskeet.uk
Date와 Time API
- 기계용 시간 과 인류용 시간으로 나눌 수 있다.
- 기계용 시간은 EPOCK (1970년 1월 1일 0시 0분 0초)부터 현재까지의 타임스탬프를 표현한다.
- 인류용 시간은 우리가 흔히 사용하는 연,월,일,시,분,초 등을 표현한다.
- 타임스탬프는 Instant를 사용한다.
- 특정 날짜(LocalDate) , 시간(LocalTime) , 일시(LocalDateTime)를 사용할 수 있다.
- 기간을 표현할 때는 Duration(시간 기반)과 Period(날짜 기반)을 사용할 수 있다.
- DateTimeFormatter를 사용해서 일시를 특정한 문자열로 포매팅할 수 있다.
- Immutable하고 새로운 인스턴스가 만들어진다.
지금 이 순간을 기계 시간으로 표현 하는 방법
Instant.now()
- 현재 UTC (GMT)를 리턴한다.
Instant instant = Instant.now();
System.out.println(instant);
// 현재 시간은 2021-01-14 22:08분
// 출력 - 2021-01-14T13:08:28.794934700Z
// 기준 시간이 UTC , GMT 이기 때문에 시간이 다르다.
ZoneId zone = ZoneId.systemDefault();
System.out.println(zone);
// 출력 - Asia/Seoul
ZonedDateTime zonedDateTime = instant.atZone(zone);
System.out.println(zonedDateTime);
// 출력 - 2021-01-14T22:11:49.055336800+09:00[Asia/Seoul]
인류용 일시를 표현하는 방법
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
// 현재 시간은 20210-01-14 22:16
// 출력 - 2021-01-14T22:16:06.431744200
LocalDateTime birth =
LocalDateTime.of(1993 , Month.APRIL , 30 , 0 , 0 , 0);
System.out.println(birth);
// 출력 - 1993-04-30T00:00
ZonedDateTime nowInKorea = ZonedDateTime.now(ZoneId.of("Asia/Seoul"));
System.out.println(nowInKorea);
// 출력 - 2021-01-14T22:18:52.191717500+09:00[Asia/Seoul]
Instant beforeInstant = Instant.now();
ZonedDateTime zonedDateTime1 = beforeInstant.atZone(ZoneId.of("Asia/Seoul"));
Instant afterInstant = zonedDateTime1.toInstant();
// ZonedDateTime 과 Instant는 서로 변환이 가능하다.
기간을 표현하는 방법
LocalDate today = LocalDate.now(); // 2021-01-14
LocalDate dateOfBirth = LocalDate.of(1993 , Month.APRIL , 30);
Period period = Period.between(dateOfBirth , today);
System.out.println(period.getYears()); // 27
System.out.println(period.getMonths()); // 8
System.out.println(period.getDays()); // 15
Period period1 = dateOfBirth.until(today);
System.out.println(period1.get(ChronoUnit.DAYS)); // 15
Instant now2 = Instant.now();
Instant plus = now2.plus(10, ChronoUnit.DAYS);
Duration diff = Duration.between(now2 , plus);
System.out.println(diff); // PT240H
포맷팅
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
System.out.println(now.format(formatter)); // 2021-01-14
미리 정의된 포맷
파싱
DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.parse("2021/01/14", parseFormatter);
System.out.println(localDate); // 2021-01-14
레거시 API 지원
(기존 Date , GregorianCalendar 변환 가능)
Date date = new Date();
// Instant <- Date
Instant instant1 = date.toInstant();
// Date <- Instant
Date newDate = Date.from(instant1);
GregorianCalendar gregorianCalendar = new GregorianCalendar();
// Instant <- GregorianCalendar
Instant toInstant = gregorianCalendar.toInstant();
// ZonedDateTime <- GregorianCalendar
ZonedDateTime toZonedDateTime = gregorianCalendar.toInstant()
.atZone(ZoneId.systemDefault());
// LocalDateTime <- GregorianCalendar
LocalDateTime toLocalDateTime = gregorianCalendar.toInstant()
.atZone(ZoneId.systemDefault()).toLocalDateTime();
// GregorianCalendar <- toZonedDateTime
GregorianCalendar from = GregorianCalendar.from(toZonedDateTime);
참고
https://docs.oracle.com/javase/tutorial/datetime/overview/index.html https://docs.oracle.com/javase/tutorial/datetime/iso/overview.html
더 자바, Java 8 - 인프런
자바 8에 추가된 기능들은 자바가 제공하는 API는 물론이고 스프링 같은 제 3의 라이브러리 및 프레임워크에서도 널리 사용되고 있습니다. 이 시대의 자바 개발자라면 반드시 알아야 합니다. 이
www.inflearn.com