Java 길찾기/이것이 자바다

[Java] 기본 API 클래스 - java.time 패키지

Kindbeeeear_ 2022. 3. 10. 20:12

자바 7 이전까지는 Date 와 Calendar 클래스를 이용해서 날짜와 시간 정보를 얻을 수 있었다. Date 클래스의 대부분의 메소드는 Deprecated되었고, Date의 용도는 단순히 특정 시점의 날짜 정보를 저장하는 역할만 한다. Calendar 클래스는 날짜와 시간 정보를 얻기에는 충분하지만, 날짜와 시간을 조작하거나 비교하는 기능이 불충분하다. 그래서 자바 8부터 날짜와 시간을 나타내는 여러 가지 API를 새롭게 추가했다. 이 API는 java.util 패키지에 없고 별도로 java.time 패키지와 하위 패키지로 제공된다.

패키지 설명
java.time 날짜와 시간을 나타내는 핵심 API인 LocalDate, LocalTime, LocalDateTime, ZonedDateTime을 포함하고 있다. 이 클래스들은 ISO-8601에 정의된 달력 시스템에 기초한다.
java.time.chrono ISO-8601에 정의된 달력 시스템 이외에 다른 달력 시스템이 필요할 때 사용할 수 있는 API들이 포함되어 있다.
java.time.format 날짜와 시간을 파싱하고 포맷팅하는 API들이 포함되어 있다.
java.time.temporal 날짜와 시간을 연산하기 위한 보조 API들이 포함되어 있다.
java.time.zone 타임존을 지원하는 API들이 포함되어 있다.

 

날짜와 시간 객체 생성

java.time 패키지에는 다음과 같이 날짜와 시간을 표현하는 5개의 클래스가 있다.

클래스명 설명
LocalDate 로컬 날짜 클래스
LocalTime 로컬 시간 클래스
LocalDateTime 로컬 날짜 및 시간 클래스(LocalDate + LocalTime)
ZonedDateTime 특정 타임존(TimeZone)의 날짜와 시간 클래스
Instant 특정 시점의 Time-Stamp 클래스

 

LocalDate

LocalDate는 로컬 날짜 클래스로 날짜 정보만을 저장할 수 있다. LocalDate 객체는 두 가지 정적 메소드로 얻을 수 있는데, now()는 컴퓨터의 현재 날짜 정보를 저장한 LocalDate 객체를 리턴하고 of()는 매개값으로 주어진 날짜 정보를 저장한 LocalDate 객체를 리턴한다.

LocalDate currDate = LocalDate.now();
LocalDate targetDate = LocalDate.of(int year, int month, int dayOfMonth);

 

LocalTime

LocalTime은 로컬 시간 클래스로 시간 정보만을 저장할 수 있다. LocalTime 객체도 마찬가지로 두 가지 정적 메소드로 얻을 수 있는데, now()는 컴퓨터의 현재 시간 정보를 저장한 LocalTime 객체를 리턴하고 of()는 매개값으로 주어진 시간 정보를 저장한 LocalTime 객체를 리턴한다.

LocalTime currTime = LocalTime.now();
LocalTime targetTime = LocalTime.of(int hour, int minute, int second, int nanoOfSecond);

 

LocalDateTime

LocalDateTime은 LocalDate와 LocalTime을 결합한 클래스라고 보면 되는데, 날짜와 시간 정보를 모두 저장할 수 있다. LocalDateTime 객체도 마찬가지로 두 가지 정적 메소드로 얻을 수 있는데, now()는 컴퓨터의 현재 날짜와 정보를 저장한 LocalDateTime 객체를 리턴하고 of()는 매개값으로 주어진 날짜와 시간 정보를 저장한 LocalDateTime 객체를 리턴한다.

LocalDateTime currDateTime = LocalDateTime.now();
LocalDateTime targetTime = LocalDateTime.of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond);

 

ZonedDateTime

ZonedDateTime은 ISO-8601 달력 시스템에서 정의하고 있는 타임존(time-zone)의 날짜와 시간을 정의하는 클래스이다. 저장 형태는 2022-03-10T18:23:55.017+09:00[Asia/Seoul]와 같이 맨 뒤에 타임존에 대한 정보(존오프셋[존아이디])가 추가적으로 붙는다. 존오프셋(ZoneOffset)은 협정세계시(UTC: Universal Time Coordinated)와 차이 나는 시간을 말한다. ZonedDateTime은 now()정적 메소드에 ZoneId를 매개값으로 주고 얻을 수 있다. ZoneId는 of() 메소드로 얻을 수 있는데, of()의 매개값은 java.TimeZone의 getAvailableIDs() 메소드가 리턴하는 유효한 값 중 하나이다.

ZoneDateTime utcDateTime = ZoneDateTime.now(ZoneId,of("UTC"));
ZoneDateTime londonDateTime = ZoneDateTime.now(ZoneId.of("Europe/London"));
ZoneDateTime seoulDateTime = ZoneDateTime.now(ZoneId.of("Asia/Seoul"));

 

Instant

Instant 클래스는 날짜와 시간의 정보를 얻거나 조작하는데 사용되지 않고, 특정 시점의 타임스탬프(Time-Stamp)로 사용된다. 주로 특정한 두 시점 간의 시간적 우선순위를 따질 때 사용한다. java.util.Date와 가장 유사한 클래스이지만, 차이점은 Date는 로컬 컴퓨터의 현재 날짜와 시간 정보를 기준으로 하지만 Instant는 협정세계시(UTC)를 기준으로 한다.

Instant instant1 = Instant.now();
Instant instant2 = Instant.now();
if(instant1.isBefore(intstant2)) { System.out.println("instant1이 빠릅니다."); }
else if(instant1.isAfter(intstant2)) { System.out.println("instant1이 늦습니다."); }
else { System.out.println("동일한 시간입니다."); }
System.out.println("차이(nanos): " + instant1.until(instant2, ChronoUnit.NANOS));

 

위 코드에서 isBefor(), isAfter()는 시간의 앞뒤 여부를 확인하는 메소드이고, until() 메소드는 두 시점 간의 차이를 리턴한다. 

 

날짜와 시간에 대한 정보 얻기

LocalDate와 LocalTime은 프로그램에서 날짜와 시간 정보를 이용할 수 있도록 다음과 같은 메소드를 제공하고 있다.

클래스 리턴 타입 메소드(매개 변수) 설명
LocalDate int getYear()
Month getMonth() Month 열거값
int getMonthValue()
int getDayOfYear 일년의 몇 번째 일
int getDayOfMonth() 월의 몇 번째 일
DayOfWeek getDayOfWeek() 요일
boolean isLeapYear() 운년 여부
LocalTime int getHour() 시간
int getMinute()
int getSecond()
int getNano() 나노초 리턴

 

LocalDateTime과 ZonedDateTime은 날짜와 시간 정보를 모두 갖고 있기 때문에 위 표에 나와 있는 대부분의 메소드를 가지고 있다. 단, isLeapYear()는 LocalDate에만 있기 때문에 toLocalDate() 메소드로 LocalDate로 변환한 후에 사용할 수 있다. ZonedDateTime은 시간 존에 대한 정보를 제공하는 다음 메소드들을 추가적으로 가지고 있다.

클래스 리턴 타입 메소드(매개 변수) 설명
ZonedDateTime ZoneId getZone() 존아이디를 리턴(예: Asiz/Seoul)
ZoneOffset getOffset() 존오프셋(시차)을 리턴

 

// DateTimeInfoExample.java -- 날짜와 시간 정보
public class DateTimeInfoExample {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        
        String strDateTime = now.getYear() + "년 ";
        strDateTime += now.getMonthValue() + "월 ";
        strDateTime += now.getDayOfMonth() + "일 ";
        strDateTime += now.getDayOfWeek() + " ";
        strDateTime += now.getHour() + "시 ";
        strDateTime += now.getMinute() + "분 ";
        strDateTime += now.getSecond() + "초 ";
        strDateTime += now.getNano() + "나노초";
        System.out.println(strDateTime + "\n");
        
        LocalDate nowDate = now.toLocalDate();
        if(nowDate.isLeapYear()) {
            System.out.println("올해는 윤년: 2월은 29일까지 있습니다.\n");
        } else {
            System.out.println("올해는 평년: 2월은 28일까지 있습니다.\n");
        }
        
        // 협정 세계시와 존오프셋
        ZonedDateTime utcDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
        System.out.println("협정 세계시: " + utcDateTime);
        ZonedDateTime seoulDateTime = ZonedDateTime.now(ZonId.of("Asia/Seoul"));
        System.out.println("서울 타임존: " + seoulDateTime);
        ZoneId seoulZoneId = seoulDateTime.getZone();
        System.out.println("서울 존아이디: " + seoulZoneId);
        ZoneOffset seoulZoneOffset = seoulDateTime.getOffset();
        System.out.println("서울 존오프셋: " + seoulZoneOffset + "\n");
    }
}

 

날짜와 시간을 조작하기

날짜와 시간 클래스들은 날짜와 시간을 조작하는 메소드와 상대 날짜를 리턴하는 메소드들을 가지고 있다.

 

빼기와 더하기

다음은 날짜와 시간을 빼거나 더하는 메소드들이다.

클래스 리턴 타입 메소드(매개 변수) 설명
LocalDate
LocalDateTime
ZonedDateTime
LocalDate
LocalDateTime
ZonedDateTime
minusYears(long) 년 빼기
minusMonths(long) 달 빼기
minusWeeks(long) 주 빼기
minusDays(long) 일 빼기
plusYears(long) 년 더하기
plusMonths(long) 달 더하기
plusWeeks(long) 주 더하기
plusDays(long) 일 더하기
LocalTime
LocalDateTime
ZonedDateTime
LocalTime
LocalDateTime
ZonedDateTime
minusHours(long) 시간 빼기
minusMinutes(long) 분 빼기
minusSeonds(long) 초 빼기
minusNanos(long) 나노초 빼기
plusHours(long) 시간 더하기
plusMinutes(long) 분 더하기
plusSeconds(long) 초 더하기
plusNanos(long) 나노초 더하기

 

각 메소드들은 수정된 LocalDate, LocalTime, LocalDateTime, ZonedDateTime을 리턴하기 때문에 도트( . ) 연산자로 연결해서 순차적으로 호출할 수 있다. 다음 예제는 현재 날짜와 시간을 얻어 1년을 더하고, 2달을 빼고, 3일을 더하고, 4시간을 더하고, 5분을 빼고, 6초를 더한 날짜와 시간을 얻는다.

// DateTimeOperationExample.java -- 날짜와 시간 연산
public class DateTimeOperationExample {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println("현재시: " + now);
        
        LocalDateTime targetDateTime = now
            .plusYears(1)
            .minusMonths(2)
            .plusDays(3)
            .plusHours(4)
            .minusMinutes(5)
            .plusSeconds(6);
        System.out.println("연산후: " + targetDateTime);
    }
}

 

변경하기

다음은 날짜와 시간을 변경하는 메소드들이다.

클래스 리턴 타입 메소드(매개 변수) 설명
LocalDate
LocalDateTime
ZonedDateTime
LocalDate
LocalDateTime
ZonedDateTime
withYear(int) 년 변경
withMonth(int) 월 변경
withDayOfMonth(int) 월의 일 변경
withDayOfYear(int) 년의 일 변경
with(TemporalAdjuster adjuster) 상대 변경
LocalTime
LocalDateTime
ZonedDateTime
LocalTime
LocalDateTime
ZonedDateTime
withHour(int) 시간 변경
withMinute(int) 분 변경
withSecond(int) 초 변경
withNano(int) 나노초 변경

 

with(TemporalAdjuster adjuster) 메소드를 제외한 나머지는 메소드 이름만 보면 어떤 정보를 수정하는지 알 수 있다. with() 메소드는 상대 변경이라고 설명되어 있는데, 이것은 현재 날짜를 기준으로 해의 첫 번째 일 또는 마지막 일, 달의 첫 번째 일 또는 마지막 일, 달의 첫 번째 요일, 지난 요일 및 돌아오는 요일 등 상대적인 날짜를 리턴한다. 매개값은 TemporalAdjuster 타입으로 다음 표에 있는 TemporalAdjuster의 정적 메소드를 호출하면 얻을 수 있다.

리턴 타입 메소드(매개 변수) 설명
TemporalAdjuster firstDayOfYear() 이번 해의 첫 번째 일
lastDayOfYear() 이번 해의 마지막 일
firstDayOfNextYear() 다음 해의 첫 번째 일
firstDayOfMonth() 이번 달의 첫 번째 일
lastDayOfMonth 이번 달의 마지막 일
firstDayOfNextMonth() 다음 달의 첫 번째 일
firstInMonth(DayOfWeek dayOfWeek) 이번 달의 첫 번째 요일
lastInMonth(DayOfWeek dayOfWeek) 이번 달의 마지막 요일
next(DayOfWeek dayOfWeek) 돌아오는 요일
nextOrSame(DayOfWeek dayOfWeek) 돌아오는 요일(오늘 포함)
previous(DayOfWeek dayOfWeek) 지난 요일
previousOrSame(DayOfWeek dayOfWeek) 지난 요일(오늘 포함)

 

// DateTimeChangeExample.java -- 날짜와 시간 변경
public class DateTimeChangeExample {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println("현재: " + now);
        
        LocalDateTime targetDateTime = null;
        
        // 직접 변경
        targetDateTeim = now
            .withTear(2024)
            .withMonth(10)
            .withDayOfMonth(5)
            .withHour(13)
            .withMinute(30)
            .withSecond(20);
        System.out.println("직접 변경: " + targetDateTime);
        
        // 년도 상대 변경
        targetDateTime = now.with(TemporalAdjusters.firstDayOfYear());
        System.out.println("이번 해의 첫 일: " + targetDateTime);
        targetDateTime = now.with(TemporalAdjusters.lastDayOfYear());
        System.out.println("이번 해의 마지막 일: " + targetDateTime);
        targetDateTime = now.with(TemporalAdjusters.firstDayOfNextYear());
        System.out.println("다음 해의 첫 일: " + targetDateTime);
        
        // 월 상대 변경
        targetDateTime = now.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("이번 달의 첫 일: " + targetDateTime);
        targetDateTime = now.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("이번 달의 마지막 일: " + targetDateTime);
        targetDateTime = now.with(TemporalAdjusters.firstDayOfNextMonth());
        System.out.println("다음 달의 첫 일: " + targetDateTime);
        
        // 요일 상대 변경
        targetDateTime = now.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
        System.out.println("이번 달의 첫 월요일: " + targetDateTime);
        targetDateTime = now.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
        System.out.println("돌아오는 월요일: " + targetDateTime);
        targetDateTime = now.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
        System.out.println("지난 월요일: " + targetDateTime);
    }
}

 

날짜와 시간을 비교하기

날짜와 시간 클래스들은 다음과 같이 비교하거나 차이를 구하는 메소드들을 가지고 있다.

클래스 리턴 타입 메소드(매개 변수) 설명
LocalDate
LocalDateTime
bolean isAfter(ChronoLocalDate other) 이후 날짜인지 비교
isBefore(ChronoLocalDate other) 이전 날짜인지 비교
isEqual(ChronoLocalDate other) 동일 날짜인지 비교
LocalTime
LocalDateTime
boolean isAfter(LocalTime other) 이후 시간인지 비교
isBefore(LocalTime other) 이전 시간인지 비교
LocalDate Period until(ChronoLocalDate endDateExclusive) 날짜 차이
LocalDate
LocalTime
LocalDateTime
long until(
  Temporal endExclusive,
  TemporalUnit unit
)
시간 차이
Period Period between(
  LocalDate startDateInclusive,
  LocalDate endDateExclusive
)
날짜 차이
Duration Duration between(
  Temporal startInclusive,
  Temporal endExclusive
)
시간 차이
ChronoUnit.YEARS long between(
  Temporal temporal1Inclusive,
  Temporal temporal2Exclusive
)
전체 년 차이
ChronoUnit.MONTHS 전체 달 차이
ChronoUnit.WEEKS 전체 주 차이
ChronoUnit.DAYS 전체 일 차이
ChronoUnit.HOURS 전체 시간 차이
ChronoUnit.SECONDS 전체 초 차이
ChronoUnit.MILLIS 전체 밀리초 차이
ChronoUnit.NANOS 전체 나노초 차이

 

Period와 Duration은 날짜와 시간의 양을 나타내는 클래스들이다. Period는 년, 달, 일의 양을 나타내는 클래스이고, Duration은 시, 분, 초, 나노초의 양을 타나내는 클래스이다. 이 클래스들은 D-day나 D-time을 구할 때 사용될 수 있다. 다음은 Period와 Duration에서 제공하는 메소드들이다.

클래스 리턴 타입 메소드(매개 변수) 설명
Period int getYears() 년의 차이
int getMonths 달의 차이
int getDays() 일의 차이
Duration int getSeconds() 초의 차이
int getNano() 나노초의 차이

 

between() 메소드는 Period와 Duration 클래스, 그리고 ChronoUnit 열거 타입에도 있다. Period와 Duration의 between()은 년, 달, 일, 초의 단순 차이를 리턴하고, ChronoUnit 열거 타입의 between()은 전체 시간을 기준으로 차이를 리턴한다. 예를 들어 2023년 1월과 2024년 3월의 달의 차이를 구할 때 Period의 between()은 2가 되고 ChronoUnit.MONTHS.between()은 14가 된다.

 

// DateTimeCompareExample.java -- 날짜와 시간 비교
public class DateTimeCompareExample {
    public static void main(String[] args) {
        LocalDateTime startDateTime = LocalDateTime.of(2023, 1, 1, 9, 0, 0);
        System.out.println("시작일: " + startDateTime);
        
        LocalDateTime endDateTime = LocalDateTime.of(2024, 3, 31, 18, 0, 0);
        System.out.println("종료일: " + endDateTime + "\n");
        //------------------------------------------------------
        if(startDateTime.isBefore(endDateTime)) {
            System.out.println("진행 중입니다." + "\n");
        } else if(startDateTime.isEqual(endDateTime)) {
            System.out.println("종료합니다." + "\n");
        } else if(startDateTime.isAfter(endDateTime)) {
            System.out.println("종료했습니다." + "\n");
        }
        //------------------------------------------------------
        System.out.println("[종료까지 남은 시간]");
        long remainYear = startDateTime.until(endDateTime, ChronoUnit.YEARS);
        long remainMonth = startDateTime.until(endDateTime, ChronoUnit.MONTHS);
        long remainDay = startDateTime.until(endDateTime, ChronoUnit.DAYS);
        long remainHour = startDateTime.until(endDateTime, ChronoUnit.HOURS);
        long remainMinute = startDateTime.until(endDateTime, ChronoUnit.MINUTES);
        long remainSecond = startDateTime.until(endDateTime, ChronoUnit.SECONDS);
        
        remainYear = ChronoUnit.YEARS.between(StartDateTime, endDateTime);
        remainMonth = ChronoUnit.MONTHS.between(StartDateTime, endDateTime);
        remainDay = ChronoUnit.DAYS.between(StartDateTime, endDateTime);
        remainHour = ChronoUnit.HOURS.between(StartDateTime, endDateTime);
        remainSecond = ChronoUnit.SECONDS.between(StartDateTime, endDateTime);
        
        System.out.println("남은 해: " + remainYear);
        System.out.println("남은 달: " + remainMonth);
        System.out.println("남은 일: " + remainDay);
        System.out.println("남은 시간: " + remainHour);
        System.out.println("남은 분: " + remainMinute);
        System.out.println("남은 초: " + remainSecond + "\n");
        //------------------------------------------------------
        System.out.println("[종료까지 남은 기간]");
        Period period =
        Period.between(startDateTime.toLocalDate(), endDateTime.toLocalDate());
        System.out.print("남은 기간: " + period.getYears() + "년 ");
        System.out.print(period.getMonths() + "달 ");
        System.out.println(period.getDays() + "일\n");
        //------------------------------------------------------
        Duration duration =
        Duration.between(startDateTime.toLocalTime(), endDateTime.toLocalTime());
        System.out.println("남은 초: " + duration.getSeconds());
    }
}

 

파싱과 포맷팅

날짜와 시간 클래스는 문자열을 파싱(parsing)해서 날짜와 시간을 생성하는 메소드와 이와 반대로 날짜와 시간을 포맷팅(Formatting)된 문자열로 변환하는 메소드를 제공하고 있다.

 

파싱(Parsing) 메소드

다음은 날짜와 시간 정보가 포함된 문자열을 파싱해서 날짜와 시간을 생성하는 두 개의 parse() 정적 메소드이다.

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

 

LocalDate의 parse(CharSequence) 메소드는 기본적으로 ISD_LOCAL_DATE 포맷터를 사용해서 문자열을 파싱한다. ISO_LOCAL_DATE는 DateTimeFormatter의 상수로 정의되어 있는데, "2024-05-03" 형식의 포맷터이다.

LocalDate localDate = LocalDate.parse("2024-05-21");

 

만약 다른 포맷터를 이용해서 문자열을 파싱하고 싶다면 parse(CharSequence, DateTimeFormatter) 메소드를 사용할 수 있다. DateTimeFormatter는 ofPattern() 메소드로 정의할 수도 있는데, 다음 코드는 "2024.05.21" 형식의 DateTimeFormatter를 정의하고 문자열을 파싱했다.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd");
LocalDate localDate = LocalDate.parse("2024.05.21", formatter);

 

ofPattern() 메소드의 매개값으로 사용되는 패턴 기호에 대한 설명은 API 도큐먼트의 java.time.format.DateTimeFormatter 클래스 설명 부분에 "Patterns for Formatting and Parsing"이란 제목으로 잘 나와 있으니 참조하길 바란다. DateTimeFormatter에는 표준화된 포맷터들이 다음과 같이 상수로 미리 정의되어 있기 때문에 ofPattern() 메소드를 사용하지 않고 바로 이용할 수 있다.

상수 설명
BASIC_ISO_DATE Basic ISO date "20111203"
ISO_LOCAL_DATE ISO Local Date "2011-12-03"
ISO_OFFSET_DATE ISO Date with offset "2011-12-03+01:00"
ISO_DATE ISO Date with or without offset "2011-12-03+01:00";"2011-12-03"
ISO_LOCAL_TIME Time without offset "10:15:30"
ISO_OFFSET_TIME Time with offset "10:15:30+01:00"
ISO_TIME Time with of without offset "10:15:30+01:00";"10:15:30"
ISO_LOCAL_DATE_TIME ISO Local Date and Time "2011-12-03T10:15:30"
ISO_OFFSET_DATE_TIME Date Time with Offset "2011-12-03T10:15:30+01:00"
ISO_ZONED_DATE_TIME Zoned Date Time "2011-12-03T10:15:30+01:00[Europe/Paris]"
ISO_DATE_TIME Date and time with ZoneId "2011-12-03T10:15:30+01:00[Europe/Paris]"
ISO_ORDINAL_DATE Year and day of year "2012-337"
ISO_WEEK_DATE Year and Week "2012-W48-6"
ISO_INSTANT Date and Time of an Instant "2011-12-03T10:15:30Z"
RFC_1123_DATE_TIME RFC 1123 / RFC 822 "Tue, 3 Jun 2008 11:05:30 GMT"

 

예를 들어 parse(CharSequence)와 동일하게 "2024-05-21"이라는 문자열을 파싱해서 LocalDate 객체를 얻고 싶다면 다음과 같이 코드를 작성하면 된다.

LocalDate localDate = LocalDate.parse("2024-05-21", DateTimeFormatter.ISO_LOCAL_DATE);

만약 포맷터의 형식과 다른 문자열을 파싱하게 되면 DateTimeParseException이 발생한다.

 

//  DateTimeParsingExample.java -- 문자열 파싱
public class DateTimeParsingExample {
    public static void main(String[] args) {
        DateTimeFormatter formatter;
        LocalDate localDate;
        
        localDate = LocalDate.parse("2024-05-21");
        System.out.println(localDate);
        
        formatter = DateTimeFormatter.ISO_LOCAL_DATE;
        localDate = LocalDate.parse("2024-05-21", formatter);
        System.out.println(localDate);
        
        formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        localDate = LocalDate.parse("2024/05/21", formatter);
        System.out.println(localDate);
        
        formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd");
        localDate = LocalDate.parse("2024.05.21", formatter);
        System.out.println(localDate);
    }
}

 

포맷팅(Formatting) 메소드

다음은 날짜와 시간을 포맷팅된 문자열로 변환시키는 format() 메소드이다.

클래스 리턴 타입 메소드(매개 변수)
LocalDate
LocalTime
LocalDateTime
ZonedDateTime
String format(Date TimeFormatter formatter)

 

format()의 매개값은 DateTimeFormatter인데 해당 형식대로 문자열을 리턴한다. 다음은 LocalDateTime으로부터 "2024년 5월 21일 오후 6시 30분"과 같은 문자열을 얻는 코드이다.

LocalDateTime now = LocalDateTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy년 M월 d일 a h시 m분");
String nowString = now.format(dateTimeFormatter);