Date와 Time

이연중·2021년 2월 1일
0

JAVA

목록 보기
12/20

Date와 Time 소개

자바 8에 새로운 날짜와 시간 APi가 생긴 이유

  • 그 전까지 사용한 java.util.Date 클래스는 mutable(객체의 상태를 바꿀 수 있음)하기 때문에 thread safe(멀티 쓰레드 환경에서 안전하게 쓰이지 않음)하지 않음
  • 클래스 이름이 명확하지 않음(Date인데 시간까지 다룸)
  • 버그 발생 여지 많음(타입 안정성이 없음(type safety x). 월이 0부터 시작하는 것 등)
  • 날짜 시간 처리가 복잡한 어플리케이션에서는 보통 Joda Time을 쓰곤 함

자바 8에서 제공하는 Date-Time API

  • JRS-310 스팩의 구현체 제공
  • 디자인 철학
    • Clear- API가 보다 명확
    • Fluent- API가 보다 유려해짐
    • Immutable
    • Extensible

주요 API

  • 기계용 시간과 인류용 시간으로 나눌 수 있음
  • 기계용 시간은 EPOCK(1970년 1월 1일 0시 0분 0초)부터 현재까지의 타임스탬프를 표현
  • 인류용 시간은 우리가 흔히 사용하는 연, 월, 일, 시, 분, 초 등을 표현
  • 타임프탬프는 Instant를 사용
  • 특정 날짜(LocalDate), 시간(LocalTime), 일시(LocalDateTime)를 사용할 수 있음
  • 기간을 표현할 때는 Duration(시간 기반)과 Period(날짜 기반)를 사용할 수 있음
  • DateTimeFormatter를 사용해 일시를 특정한 문자열로 포매팅할 수 있음

Date와 Time API

현재를 기계 시간으로 표현하는 방법

  • Instant.now(): 현재 UTC(GMT)를 리턴

  • Instant now=Instant.now();
    System.out.println(now); //기준시 UTC, GMT
    System.out.println(now.atZone(ZoneId.of("UTC")));
    
    ZoneDateTime zonedDateTime= new.atZone(ZoneId.systemDefault());
    System.out.println(zonedDateTime);

인류용 일시를 표현하는 방법

  • LocalDateTime.now(): 현재 시스템 Zone에 해당하는 일시를 리턴
  • ZonedDateTime.now(ZoneId.of(String)): 특정 Zone의 일시를 리턴
  • LocalDateTime.of(int, Month, int, int, int, int): 로컬의 특정 일시를 리턴
  • ZonedDateTime.of(int, Month, int, int, int, int, ZoneId): 특정 Zone의 특정 일시를 리턴

기간을 표현하는 방법

  • Period/Duration. between()

  • LocalDate today=LocalDate.now();
    LocalDate birthDay=LocalDate.of(2020,Month.DECEMBER,26);
    Instant now=Instant.now();
    Instant plus=now.plus(10,ChronoUnit.SECONDS); //새로운 Instant가 나옴(예전에는 x) 
    
    Period between=Period.between(today, birthDay);
    System.out.println(between.get(chronoUnit.MONTHS)); //between으로 날짜간 차이 출력
    
    Period until=today.until(birthday);
    System.out.println(util.get(ChronoUnit.DAYS)); //until로 날짜간 차이 출력
    
    Duration duration=Duration.between(now,plus);
    System.out.println(duration.getSeconds()); //기계용 시간 비교. Period는 인류용 시간 비교

파싱 또는 포매팅

  • 미리 정의해둔 포맷 참고

    https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#predefined

  • LocalDateTime.parse(String, DateTimeFormatter);

  • Dateteme

    • LocalDateTime now= LocalDateTime.now();
      DateTimeFormatter formatter=DateTimeFormatter.ofPattern("MM/d/yyyy");
      LocalDate date=LocalDate.parse("07/15/1982",formatter); //문자열을 LocalDate 타입으로 파싱
      
      System.out.println(now.format(formatter)); //02/1/2021 출력(현재 날짜). 현재 날짜를 지정한 포맷으로 출력
      System.out.println(date); //1982-07-15 출력

레거시 API 지원

  • GregorianCalendar와 Date 타입의 인스턴스를 Instant나 ZonedDateTime으로 변환 가능

  • java.util.TimeZone에서 java.time.ZoneId로 상호 변환 가능

    • ZoneId newZoneAPI= TimeZone.getTimeZone("PST").toZoneId(); //예전 API에서 최근 API로
      TimeZone legacyZoneAPI= TimeZone.getTime(newZoneAPI); //최근 API에서 예전 API로
      Instant newInstant= new Date().toInstant(); //Date에서 Instant로
      Date legacyInstant= Date.from(newInstant) //Instant에서 Date로

참고

https://www.inflearn.com/course/the-java-java8

profile
Always's Archives

0개의 댓글