Image
Kotlin/Time

Kotlin LocalDate Class를 이용하여 날짜(연, 월, 일) 다루기

1. LocalDate 만들기

객체 생성 정적 메서드를 이용하여 LocalDate 인스턴스를 만든다. 아래는 가장 많이 쓰이는 4가지 유형을 소개한다.

/* 직접 지정하여 만들기 */
val date = LocalDate.of(2021, 1, 26)

/* String을 LocalDate로 만들기 */
val dateParse = LocalDate.parse("2020-01-26")

/* DateFormatter을 지정하여 String을 LocalDate로 만들기 */
val dateParseWithFormatter = LocalDate.parse("2021-01-26", DateTimeFormatter.ISO_DATE)

/* 현재 시간을 LocalDate로 만들기 */
val dateNow = LocalDate.now()

 

2. LocalDate 에서 값 읽기

LocalDate는 날짜 값을 읽는 여러 메서드를 제공한다.

  • LocalDate에서 직접 변수에 접근하여 읽는 방법
  • ChronoField라 부르는 TemporalField를 이용하여 읽는 방법
val date: LocalDate = LocalDate.of(2021, 1, 21)

/* 년 출력하기 */
val year: Int = date.getYear() // 2021
val yearTempField: Int = date.get(ChronoField.YEAR) // 2021  - Temporal Field를 이용하여 읽음

/* 월 출력하기 */
val monthInstance: Month = date.getMonth() // January
val month: Int = monthInstance.getValue() // 1
val monthTempField: Int = date.get(ChronoField.MONTH_OF_YEAR) // 1 - Temporal Field 이용하여 읽음

/* 일 출력하기 */
val day: Int = date.getDayOfMonth() // 21
val dayTempField: Int = date.get(ChronoField.DAY_OF_MONTH) // 21 - Temporal Field 이용하여 읽음

/* 요일 출력하기 */
val dayOfWeek: DayOfWeek = date.getDayOfWeek() // TuesDay

 

3. LocalDate 속성 바꾸기

LocalDate는 불변객체이다. 따라서 속성값( 연, 월, 일 )을 바꾸려면 새로운 객체를 생성해 할당하거나 기존 객체에 재할당 해야 한다. 아래에서는 새로운 객체를 생성해 할당했다.

  • 특정 값으로 바꾸기
val date: LocalDate = LocalDate.of(2021, 1, 21)

/* 속성 하나씩 바꾸기 */
val newDate1: LocalDate = date.withYear(2029) // 2029 - 1 - 21
val newDate2: LocalDate = date.withMonth(9) // 2021 - 9 - 21
val newDate3: LocalDate = date.withDayOfMonth(29) // 2021 - 1- 29

/* 속성 연쇄적으로 바꾸기 */
val newDate4: LocalDate = date.withYear(2029).withMonth(9).withDayOfMonth(29) // 2029 - 9 - 29

 

  • 상대 값으로 바꾸기
val date: LocalDate = LocalDate.of(2021, 1, 21)
val date1: LocalDate = date.plusYears(1) // 2022 - 1 - 21
val date2: LocalDate = date.plusMonths(1) // 2021 - 2 - 21
val date3: LocalDate = date.plusWeeks(1) // 2021 - 1 - 28        
val date4: LocalDate = date.plusDays(1) // 2021 - 1 - 22

 

4. LocalDate 포메팅

개요

<1. LocalDate 만들기>에서 parse 정적 메서드 사용 시, date formatter을 이용하여 LocalDate를 만드는 방법에 대해 간단히 다루었다.

val dateParseWithFormatter: LocalDate = LocalDate.parse("2021-01-26", DateTimeFormatter.ISO_DATE)

LocalDate는 DateTimeFormatter을 이용하여 포메팅이 가능하다. 따라서 다양한 Pattern의 날짜도 모두 LocalDate로 변환이 가능하다.

DateTimeFormatter은 LocalDate, LocalTime, LocalDateTime 모두에서 사용 가능하다.

 

LocalDate 포메팅 하기

LocalDate를 포메팅 하기 위해서는 Format이 필요하다.

Format을 만들 때는 DateTimeFormatter.ofPattern()메서드를 사용하여 Format을 만든다. 아래는 예시이다.

val dateTimeFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy")
val dateParseWithFormatter: LocalDate = LocalDate.parse("26/01/2021", dateTimeFormatter)

마찬가지로 출력 시에도 이를 이용하면 다양한 형태로 출력이 가능하다.

val dateTimeFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy")
val dateParseWithFormatter: LocalDate = LocalDate.parse("26/01/2021", dateTimeFormatter)
println(dateParseWithFormatter.toString()) // 2021-01-26
println(dateParseWithFormatter.format(dateTimeFormatter)) // 26/01/2021

DateTimeFormatter에 Locale(지역)을 설정하면 각 Locale에 해당하는 언어로 출력이 가능하다.

val dateTimeFormatterKorea: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MMMM/dd", Locale.KOREA)
println(dateParseWithFormatter.format(dateTimeFormatterKorea)) // 2021/1월/26;

 

반응형

 

이 글의 저작권은 '조세영의 Kotlin World' 에 있습니다. 글, 이미지 무단 재배포 및 변경을 금지합니다.

 

 

Kotlin, Android, Spring 사용자 오픈 카톡

오셔서 궁금한 점을 질문해보세요!
비밀번호 : kotlin22

open.kakao.com