1. Date, Calendar 클래스

이전 포스팅을 보자

jino-dev-diary.tistory.com/entry/Java-Date-Calendar-%ED%81%B4%EB%9E%98%EC%8A%A4?category=941695

요약하자면, Date 클래스와 Calendar 클래스는 문제점이 많아서 대부분 다른 오픈소스 라이브러리를 사용했었다.

이를 보완하기위해 JDK 1.8부터 Time 패키지를 제공한다.


2. Time 패키지

2.1 특징

Time 패키지의 클래스들은 Date나 Calendar 클래스와 다르게 Immutable이다. 즉 날짜나 시간을 변경하면 기존의 객체가 변경되는 것이 아니라, 새로운 객체를 반환한다. (String 과 비슷함) 그러므로 멀티쓰레드 환경에서 안전하다.

2.2 핵심 클래스

LocalTime - 시간을 표현할 때 사용

LocalDate - 날짜를 표현할 때 사용

LocalDateTime - 모두 표현할 때 사용

ZonedDateTime - 시간대(time zone)까지 표현할 때 사용

2.3 객체 생성

Calendar의 경우 - Calendar.getInstance();

Date의 경우 - new Date();

Time 클래스의 경우 - now()of()를 이용

//Calendar
Calendar cal = Calendar.getInstance();
//Date
Date date = new Date();

//localDate
LocalDate dateNow = LocalDate.now();
LocalDate dateOf = Localdate.of(2020, 11, 11);
//localTime
LocalTime timeNow = LocalTime.now();
LocalTime timeOf = LocalTime.of(18, 30, 0);
//LocalDateTime
LocalDateTime dateTimeNow = LocalDateTime.now();
LocalDateTime dateTimeOf = LocalDateTime.of(dateNow, timeNow);
//ZonedDateTime
ZonedDateTime zonedDateTimeNow = ZonedDateTime.now();
ZonedDateTime zonedDateTimeOf = ZonedDateTime.of(dateOf, timeOf, ZoneId.of("Asia/Seoul"));

2.4 필드 값 가져오기

get~() 메서드 사용

클래스 리턴 타입 메서드 설명
LocalDate
LocalDateTime
ZonedDateTime
int getYear()
Month getMonth() Month값
int getMonthValue()
int getDayOfYear() 일년 중 몇 번째 일
int getDayOfMonth() 월 중 몇 번째 일
DayOfWeek getDayOfWeek() 요일
boolean isLeapYear() 윤년 여부
LocalTime
LocalDateTime
ZonedDateTime
int getHour() 시간
int getMinute()
int getSecond()
int getNano() 나노초
ZonedDateTime ZoneId getZone() Asia/Seoul 등..
ZoneOffset getOffset() UTC와의 시차 리턴

예시 코드

public class TimeTest {

  public static void localDateTimeTest() {
    LocalDateTime dateTime = LocalDateTime.now();
    //date
    int month = dateTime.getMonthValue();
    int year = dateTime.getYear();
    int day = dateTime.getDayOfMonth();
    String dayOfWeek = dateTime.getDayOfWeek().name();

    //time
    int hour = dateTime.getHour();
    int minute = dateTime.getMinute();
    int second = dateTime.getSecond();
  }
}

2.5 필드 변경

with~(long ), plus~(long ), minus~(long )사용하여 년, 월, 주, 일, 시간, 분, 초, 나노초를 더하거나 뺄 수 고, 변경할 수 있다.

클래스 리턴 타입 메서드(매개 변수 타입) 설명
LocalDate
LocalDateTime
ZonedDateTime
LocalDate
LocalDateTime
ZonedDateTime
with/plus/minusYears(long) 년 변경
with/plus/minusMonths(long) 월 변경
with/plus/minusWeeks(long) 주 변경
with/plus/minusDays(long) 일 변경
LocalTime
LocalDateTime
ZonedDateTime
LocalTime
LocalDateTime
ZonedDateTime
with/plus/minusHours(long) 시간 변경
with/plus/minusMinutes(long) 분 변경
with/plus/minusSeconds(long) 초 변경
with/plus/minusNanos(long) 나노초 변경

결과값은 항상 새로운 객체를 생성해서 반환하기 때문에 대입연산자 이용해야한다

with(TemporalAdjusters adjuster) 메서드를 통해 현자 날짜를 기준으로 년도의 첫 번째 일, 마지막 일, 돌아오는 요일 등 상대적인 날짜로 변경할 수 있다.

TemporalAdjusters 메서드(매개 변수) 설명
firstDayOfYear() 이번 해의 첫 번째 일
lastDayOfYear() 이번 해의 마지막 일
firstDayOfNextYear() 다음 해의 첫 번째 일
firstDayOfMonth() 이번 달의 첫 번째 일
lastDayOfMonth() 이번 달의 마지막 일
firstDayOfNextMonth() 다음 달의 첫 번째 일
firstInMonth(DayOfWeek) 이번 달의 첫 번째 요일
lastInMonth(DayOfWeek) 이번 달의 마지막 요일
next(DayOfWeek) 다음 요일
nextOrSame(DayOfWeek) 다음 요일 (오늘 포함)
previous(DayOfWeek) 저번 요일
previousOrSame(DayOfWeek) 저번 요일 (오늘 포함)

예시코드

public class TimeTest {

  public static void localDateTimeTest() {
    LocalDateTime dateTime = LocalDateTime.now();
    dateTime = dateTime.plusWeeks(2);
    dateTime = dateTime.minusWeeks(2).plusHours(3);
    dateTime = dateTime.plusMinutes(30);
    dateTime = dateTime.withMonth(5);

    //작성 기준 오늘이 수요일인데 nextOrSame인 경우 오늘이다. next인 경우는 다음주 수요일
    LocalDateTime dateTime2 = dateTime.with(TemporalAdjusters.nextOrSame(DayOfWeek.WEDNESDAY));

  }
}

2.5 날짜와 시간 비교

LocalDate, LocalDateTime, ZonedDateTime의 isAfter(ChronoLocalDate ohter), isBefore(ChronoLocalDate ohter), isEqual(ChronoLocalDate other) 메서드 이용하여 날짜를 비교할 수 있다. 리턴 타입은 boolean이다.

또한 LocalTime은 isAfter(LocalTime other), isBefore(LocalTime other) 메서드를 이용해 시간을 비교할 수 있다. 리턴 타입은 역시 boolean

클래스 리턴 타입 매서드(매개 변수) 설명
LocalDate
LocalDateTime
ZonedDateTime
boolean isAfter(ChronoLocalDate) 이후 날짜인지 비교
isBefore(ChronoLocalDate) 이전 날짜인지 비교
isEqual(ChrononoLocalDate) 같은 날짜인지 비교
LocalTime boolean isAfter(LocalTime) 이후 시간인지 비교
isBefore(LocalTime) 이전 시간인지 비교

예시 코드

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;

public class DateTimeTest {

  @Test
  public void testCompareDate() {
    LocalDate localDate = LocalDate.now();
    LocalDateTime localDateTime = LocalDateTime.now();
    ZonedDateTime zonedDateTime = ZonedDateTime.now();

    LocalDate past = LocalDate.of(2018, 11, 11);
    LocalDateTime future = LocalDateTime.of(2022, 12, 25, 12, 0, 0);
    ZonedDateTime now = ZonedDateTime.now();

    assertTrue(localDate.isAfter(past));       
    assertFalse(localDateTime.isAfter(future));
    assertTrue(zonedDateTime.isEqual(now));
    assertTrue(localDate.isBefore(future)); //컴파일 오류 : 같은 클래스끼리 비교가능
    assertTrue(localDate.isEqual(now));     //컴파일 오류 : 같은 클래스끼리 비교가능
  }

  @Test
  public void testCompareTime() {
    LocalTime localTime = LocalTime.now();

    LocalTime past = LocalTime.of(12, 0, 0);

    assertTrue(localTime.isAfter(past));
  }
}

2.6 날짜와 시간 차이 계산하기

LocalDate는 until(ChronoLocalDate endDateExclusive) 메서드를 통해 날짜 차이를 계산할 수 있다. 리턴 타임은 java.time.Period 이다. Period 클래스의 getYears(), getMonths(), getDays() 메서드를 통해 년, 월, 일의 차이를 계산할 수 있다.

또한 Period 클래스의 between(LocalDate startDateInclusive, LocalDate endDateInclusive) 메서드를 사용해서도 날짜 차이를 구할 수 있다. 리턴 타입은 Period 이다.

클래스 리턴 타입 메서드(매개 변수) 설명
LocalDate Period until(ChronoLocalDate) 날짜 차이
Period between(LocalDate, LocalDate)

예시 코드

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;

public class DateTimeTest {

  @Test
  public void testCalculateDifferenceOfDate() {
    LocalDate localDate = LocalDate.now();

    LocalDate past = LocalDate.of(2017, 8, 15);
    LocalDate future = LocalDate.of(2020, 12, 25);

    //LocalDate의 until() 사용
    Period differences = localDate.until(past);
    assertThat(differences.getYears(), is(-3));
    assertThat(differences.getMonths(), is(-2));
    assertThat(differences.getDays(), is(-27));

    //Period의 between() 사용
    differences = Period.between(localDate, past);
    assertThat(differences.getYears(), is(-3));
    assertThat(differences.getMonths(), is(-2));
    assertThat(differences.getDays(), is(-27));

    //LocalDate의 until() 사용
    differences = localDate.until(future);
    assertThat(differences.getYears(), is(0));
    assertThat(differences.getMonths(), is(1));
    assertThat(differences.getDays(), is(14));

    //Period의 between() 사용
    differences = Period.between(localDate, future);
    assertThat(differences.getYears(), is(0));
    assertThat(differences.getMonths(), is(1));
    assertThat(differences.getDays(), is(14));
  }
}

그런데 이 경우에는 전체 시간을 기준으로 계산할 수가 없다. 2020-11-11과 2020-12-25는 1개월 14일 차이나지만 44일 차이나기도 한다. 44를 구하기 위해서 ChronoUnit.DAYS의 between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) 메서드를 사용한다.

ChronoUnit 설명
ChronoUnit.YEARS 전체 년 차이
ChronoUnit.MONTHS 전체 월 차이
ChronoUnit.DAYS 전체 일 차이
ChronoUnit.HOURS 전체 시간 차이
ChronoUnit.MINUTES 전체 분 차이
ChronoUnit.SECONDS 전체 초 차이

예시 코드

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;

public class DateTimeTest {

  @Test
  public void testCalculateDifferenceOfDate() {
    LocalDate localDate = LocalDate.now();

    LocalDate past = LocalDate.of(2017, 8, 15);
    LocalDate future = LocalDate.of(2020, 12, 25);

    assertThat(ChronoUnit.YEARS.between(localDate,future), is(0L));
    assertThat(ChronoUnit.MONTHS.between(localDate,future), is(1L));
    assertThat(ChronoUnit.DAYS.between(localDate,future), is(44L));
    //until(Temporal endExclusive, TemporalUnit unit)을 사용해도 됨
    assertThat(localDate.until(future, ChronoUnit.DAYS), is(44L));
  }
}

시간 차이는 LocalTime, LocalDateTime, ZonedDateTime의 until(Temporal endExclusive, TemporalUnit unit)메서드를 통해 구할 수 있다. 리턴 타입은 long이다. TemporalUnit 인터페이스의 구현테인 ChronoUnit을 이용하면 된다.

또 다른 방법으로 java.time.Duration 클래스의 between(Temporal startInclusive, Temporal endExclusive) 메서드를 이용해서 시간 차이를 구할 수 있다. 리턴 타입은 Duration이다.

클래스 리턴 타입 메서드(매개 변수) 설명
LocalTime
LocalDateTime
ZonedDateTime
long until(Temporal, TemporalUnit) 시간 차이
Duration Duration between(Temporal, Temporal)

예시 코드

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;

public class DateTimeTest {

  @Test
  public void testCalculateDifferenceOfTime() {
    LocalTime localTime = LocalTime.now();
    LocalDateTime localDateTime = LocalDateTime.now();

    LocalTime past = LocalTime.of(8, 21, 12);
    LocalDateTime future = LocalDateTime.of(LocalDate.now(), LocalTime.of(23, 59, 59));

    assertThat(localTime.until(past, ChronoUnit.HOURS), is(-13L));
    assertThat(Duration.between(localTime, past).toHours(), is(-13L));

    assertThat(localDateTime.until(future, ChronoUnit.MINUTES), is(134L));
    assertThat(Duration.between(localDateTime, future).toMinutes(), is(134L));

    Duration differences = Duration.between(localDateTime, future);
    long seconds = differences.getSeconds();
  }
}

2.7 파싱과 포맷팅

LocalDate, LocalTime, LocalDateTime, ZonedDateTime 클래스의 parse(CharSequence), parse(CharSequence, DateTimeFormatter) 메서드를 통해 문자열을 클래스로 파싱할 수 있다. DateTimeFormatter는 static 메서드인 ofPattern()을 사용한다.

parse() 메서드에서 기본 포맷은 Date는 yyyy-MM-dd이고, Time은 HH:mm:ss이다. 이외의 포맷으로 파싱을 할 경우 DateTimeFormmater를 사용한다.

클래스 리턴 타입 메서드(매개 변수)
LocalDate
LocalTime
LocalDateTime
ZonedDateTime
LocalDate
LocalTime
LocalDateTime
ZonedDateTime
parse(CharSequence)
parse(CharSequence, DateTimeFormatter)

예시 코드

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;

public class DateTimeTest {

  @Test
  public void testParseStringToDateAndTime() {
    String dateNow = "2020-11-11";
    String timeNow = "21:53:00";
    LocalDate localDate = LocalDate.parse(dateNow);
    LocalTime localTime = LocalTime.parse(timeNow);
    LocalDateTime localDateTime = LocalDateTime.parse(dateNow + "T" + timeNow);

    dateNow = "201111";
    timeNow = "21-53-12";
    assertThat(LocalDate.parse(dateNow, DateTimeFormatter.ofPattern("yyMMdd")),
        is(LocalDate.of(2020, 11, 11)));
    assertThat(LocalTime.parse(timeNow, DateTimeFormatter.ofPattern("HH-mm-ss")),
        is(LocalTime.of(21, 53, 12)));
  }
}

또한 LocalDate, LocalTime, LocalDateTime, ZonedDateTime 클래스의 format(DateTimeFormatter formatter) 메서드를 사용해서 원하는 문자열로 변환할 수 있다.

클래스 리턴 타입 메서드(매개 변수)
LocalDate
LocalTime
LocalDateTime
ZonedDateTime
String format(DateFormtter)

예시 코드

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;

public class DateTimeTest {

  @Test
  public void testFormatDateAndTimeToString() {
    LocalDate localDate = LocalDate.now();
    LocalTime localTime = LocalTime.now();

    String date = localDate.format(DateTimeFormatter.ofPattern("yyyy년 MM월 dd일"));
    String time = localTime.format(DateTimeFormatter.ofPattern("H시 m분"));

    assertThat(date, is("2020년 11월 12일"));
    assertThat(time, is("1시 8분"));
  }
}

3. 참고자료

  • 자바의 정석

+ Recent posts