Logo

[Java8 Time API] LocalDate, LocalTime, LocalDateTime 사용법

이번 포스팅에서는 Java8 Date/Time API의 LocalDateLocalTime 그리고 LocalDateTime 사용법에 대해서 알아보겠습니다. 이 3개의 클래스는 모두 타임존 개념을 가지고 있지 않기 때문에 타임존에 따른 시간 변환이 불가능하다는 공통점을 가지고 있습니다.

LocalDate

LocalDate 클래스는 타임존 개념이 필요없는 날짜 정보를 나타내기 위해서 사용됩니다. 대표적으로 적용이 가능한 사례는 ‘생일’을 떠올릴 수 있을 것 같습니다. 보통 우리가 생일을 얘기할 때는 타임존 개념을 넣지 않기 때문입니다.

LocalDate today = LocalDate.now();
System.out.println("Today is " + today);

LocalDate birthday = LocalDate.of(1982, 7, 13);
System.out.println("My birthday is " + birthday);

LocalDate christmas = LocalDate.parse("2017-12-25");
System.out.println("Last Christmas is " + christmas);
Today is 2018-06-17
My birthday is 1982-07-13
Last Christmas is 2017-12-25

위 예제 코드 처럼 LocalDate 클래스는 public 생성자를 제공하지 않기 때문에 객체를 생성할 때는 now()나, of(), parse()와 같은 정적 메소드를 사용하도록 되어 있습니다. 기본 포맷인 yyyy-MM-dd 형태의 문자열을 parse() 메소드에 넘길 수 있습니다.

LocalTime

LocalTime 클래스는 타임존 개념이 필요없는 시간 정보를 나타내기 위해서 사용됩니다. 예를 들어 기상 시간이나 취침 시간과 같은 개인 일정의 경우 대부분의 상황에서는 타임존 개념이 필요하지 않기 때문에 LocalTime을 활용할 수 있습니다.

LocalTime currentTime = LocalTime.now();
System.out.println("The current time here is " + currentTime);

LocalTime currentTimeInParis = LocalTime.now(ZoneId.of("Europe/Paris"));
System.out.println("The current time in Paris is " + currentTimeInParis);

LocalTime timeToGoToBed = LocalTime.of(23, 30, 0);
System.out.println("I go to bed at " + timeToGoToBed);

LocalTime timeToGetUp = timeToGoToBed.plusHours(8);
System.out.println("I get up at " + timeToGetUp);

System.out.println("I still go to bed at " + timeToGoToBed);
The current time here is 11:57:33.804
The current time in Paris is 04:57:33.806
I go to bed at 23:30
I get up at 07:30
I still go to bed at 23:30

객체 생성 방법은 LocalDate과 매우 흡사합니다. 기본 포맷은 HH:mm:ss.SSS 이며 plusXxx()minusXxx()와 같은 메소드를 통해서 시간이 변경된 새로운 객체를 반환할 수 있습니다. Java8 Date/Time API의 클래스들은 Immutable하기 때문에 한번 생성되면 내부 필드값을 바꿀 수 없기 때문입니다.

LocalDateTime

LocalDateTime 클래스는 타임존 개념이 필요없는 날짜와 시간 정보 모두를 나태나기 위해서 사용됩니다. 즉, 간단하게 LocalDateLocalTime을 합쳐놨다고 보시면 됩니다.

LocalDateTime now = LocalDateTime.now();
System.out.println("Now is " + now);

LocalDateTime now2 = LocalDateTime.of(LocalDate.now(), LocalTime.now());
System.out.println("Now is " + now2);

LocalDateTime y2k = LocalDateTime.parse("1999-12-31T23:59:59.999");
System.out.println("Y2K is " + y2k);

LocalDateTime dateOfBirth = LocalDateTime.of(1982, 7, 13, 14, 25, 00);
System.out.println("My date of birth is " + dateOfBirth);

LocalDateTime dateOfBirth2 = Year.of(1982).atMonth(7).atDay(13).atTime(14, 25);
System.out.println("My date of birth is " + dateOfBirth2);
Now is 2018-06-17T22:46:17.348
Now is 2018-06-17T22:46:17.408
Y2K is 1999-12-31T23:59:59.999
My date of birth is 1982-07-13T14:25
My date of birth is 1982-07-13T14:25

객체 생성 방법은 LocalDate, LocalTime과 대동소이하며 기본 포맷은 yyyy-MM-dd'T'HH-mm-ss.SSS 입니다. dateOfBirth2를 생성할 때는 정적 메소드 대신에 Year.of()로 시작하는 Fluent API를 사용하였습니다. 코드 가독성이 좋아지기 때문에 개인적으로 선호하는 방식입니다.

유틸리티 메소드

LocalDateLocalTime 그리고 LocalDateTime에서 공통적으로 제공하는 유용한 유틸리티 메소드에 대해서 간략히 살펴보도록 하겠습니다.

LocalDate today = Year.of(2017).atMonth(12).atDay(17);
System.out.println("Today : " + today);
System.out.println("Year : " + today.getYear());
System.out.println("Month : " + today.getMonth());
System.out.println("DayOfMonth : " + today.getDayOfMonth());
System.out.println("DayOfWeek : " + today.getDayOfWeek());
System.out.println("IsLeapYear : " + today.isLeapYear());

System.out.println("1 year after today: " + today.plusYears(1));
System.out.println("1 month after today: " + today.plusMonths(1));
System.out.println("1 day after today: " + today.plusDays(1));

LocalDate yesterday = today.minusDays(1);
System.out.println("Today is after yesterday? " + today.isAfter(yesterday));
System.out.println("Today is before yesterday? " + today.isBefore(yesterday));

LocalDateTime now = today.atTime(22, 46, 17, 348);
System.out.println("Now : " + now);
System.out.println("Hour: " + now.getHour());
System.out.println("Minute: " + now.getMinute());
System.out.println("Second: " + now.getSecond());
System.out.println("Nano: " + now.getNano());
Today : 2017-12-17
Year : 2017
Month : DECEMBER
DayOfMonth : 17
DayOfWeek : SUNDAY
IsLeapYear : false
1 year after today: 2018-12-17
1 month after today: 2018-01-17
1 day after today: 2017-12-18
Today is after yesterday? true
Today is before yesterday? false
Now : 2017-12-17T22:46:17.000000348
Hour: 22
Minute: 46
Second: 17
Nano: 348

이상으로 LocalDateLocalTime 그리고 LocalDateTime 사용법에 대해서 알아보았습니다.