kotlin Exception「java.time.DateTimeException: Invalid value for MonthOfYear」の解決方法

kotlin Exception「java.time.DateTimeException: Invalid value for MonthOfYear」の解決方法

kotlinで、Exception「java.time.DateTimeException: Invalid value for MonthOfYear」の解決方法を記述してます。

環境

  • OS windows11 home
  • java 17.0.2
  • kotlin 1.6.10-release-923

Exception全文

以下のコードで発生。

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

fun main(){    

    val d = LocalDateTime.now()

    var result =  d.withMonth(14).format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"))

    println(result) // 2022/12/21 12:21:54

}

Exception

Exception in thread "main" java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 14
        at java.base/java.time.temporal.ValueRange.checkValidValue(ValueRange.java:319)
        at java.base/java.time.temporal.ChronoField.checkValidValue(ChronoField.java:718)
        at java.base/java.time.LocalDate.withMonth(LocalDate.java:1104)
        at java.base/java.time.LocalDateTime.withMonth(LocalDateTime.java:1003)
        at TempCodeRunnerFileKt.main(tempCodeRunnerFile.kt:8)
        at TempCodeRunnerFileKt.main(tempCodeRunnerFile.kt)

原因

「withMonth」で指定している値が、存在しない月のため

対処法

「1~12」までの範囲で指定する

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

fun main(){    

    val d = LocalDateTime.now()

    var result =  d.withMonth(12).format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"))

    println(result)
    
}