자바 8에 새로운 날짜와 시간 API가 생긴 이유
자바 8에서 제공하는 Date-Time API
주요 API
지금 이 순간을 기계 시간으로 표현하는 방법
Instant instant = Instant.now();
System.out.println(instant); //기준시 UTC, GMT
System.out.println(instant.atZone(ZoneId.of("UTC")));
ZoneId zone = ZoneId.systemDefault();
System.out.println(zone);
ZonedDateTime zonedDateTime = instant.atZone(zone);
System.out.println(zonedDateTime);
인류용 일시를 표현하는 방법
LocalDateTime now = LocalDateTime.now();
LocalDateTime birthDay =
LocalDateTime.of(1982, Month.JUNE, 15, 0, 0, 0);
ZonedDateTime nowInKorea = ZonedDateTime.now(ZoneId.of("Asia/Seoul"));
기간을 표현하는 방법
LocalDate today = LocalDate.now();
LocalDate thisYearBirthDay = LocalDate.of(2022, Month.JUNE, 15);
Period period = Period.between(today, thisYearBirthDay);
System.out.println(period.getDays());
Period until = today.until(thisYearBirthDay);
System.out.println(until.get(ChronoUnit.DAYS));
Instant now = Instant.now();
Instant plus = now.plus(10, ChronoUnit.SECONDS);
Duration between = Duration.between(now, plus);
System.out.println(between.getSeconds());
파싱 또는 포매팅
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter MMddyy = DateTimeFormatter.ofPattern("MM/dd/yyyy");
System.out.println(now.format(MMddyy));
LocalDate parse = LocalDate.parse("07/15/1982", MMddyy);
System.out.println(parse);
레거시 API 지원
Date date = new Date();
Instant instant = date.toInstant();
Date newDate = Date.from(instant);
GregorianCalendar gregorianCalendar = new GregorianCalendar();
ZonedDateTime dateTime = gregorianCalendar.toInstant().atZone(ZoneId.systemDefault());
GregorianCalendar from = GregorianCalendar.from(dateTime);
ZoneId zoneId = TimeZone.getTimeZone("PST").toZoneId();
TimeZone timeZone = TimeZone.getTimeZone(zoneId);
LocalDateTime now = LocalDateTime.now();
LocalDateTime plus = now.plus(10, ChronoUnit.DAYS);
```