Programming/Kotlin

[Kotlin] Text '..' could not be parsed: Unable to obtain LocalDate from TemporalAccessor ์˜ค๋ฅ˜ ์›์ธ ๋ฐ ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•

yuri lee 2023. 3. 30. 21:17
๋ฐ˜์‘ํ˜•

Intro

์•ˆ๋…•ํ•˜์„ธ์š”. ์ฝ”ํ‹€๋ฆฐ ์ŠคํŠธ๋ง์„ ์ฝ”ํ‹€๋ฆฐ ๋‚ ์งœ๋กœ ๋ณ€ํ™˜ํ•˜๋˜ ๋„์ค‘ ์•„๋ž˜์™€ ๊ฐ™์€ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. 

 

import java.math.BigDecimal
import java.math.RoundingMode
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*

fun main(args: Array<String>) {
    val input = "2301"
    val formatter = DateTimeFormatter.ofPattern("yyMM",  Locale.KOREA)
    val date = LocalDate.parse(input, formatter).minusYears(1)
    val output = date.format(formatter)
    print(output)
}

Text '..' could not be parsed: Unable to obtain LocalDate from TemporalAccessor

 

How to solve the problem

๋‚ ์งœ๊ฐ’์„ 2302, yyMM ํ˜•์‹์„ ์ด์šฉํ•ด์„œ ํ™œ์šฉํ•˜๋ ค๊ณ  ํ–ˆ์ง€๋งŒ, ๊ณ„์† ์—๋Ÿฌ๊ฐ€ ๋‚ฌ์Šต๋‹ˆ๋‹ค. yyyyMM ํ˜•์‹๋„ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์—๋Ÿฌ๊ฐ€ ๋‚˜๋”๊ตฐ์š”. ๊ทธ๋ž˜์„œ ์•„๋ž˜์™€ ๊ฐ™์ด ๋ณ€๊ฒฝํ•ด์„œ ์‹คํ–‰ํ•˜๋‹ˆ ์ •์ƒ ์ž‘๋™ํ–ˆ์Šต๋‹ˆ๋‹ค. 

fun main(args: Array<String>) {
    val input = "20" + "2301" + "01"
    val formatter = DateTimeFormatter.ofPattern("yyyyMMdd",  Locale.KOREA)
    val date = LocalDate.parse(input, formatter).minusYears(1)
    val output = date.format(formatter)
    print(output) // 20220101
}

ofPatteren์— ๋…„์›”์ผ์ด (yyyyMMdd) ํ˜•ํƒœ๋กœ ๋“ค์–ด๊ฐ€์•ผ ๋˜๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค :)

๋ฐ˜์‘ํ˜•