将字符串转换为 LocalDate Kotlin

its*_*fix 6 kotlin

我想转换字符串值,这是我的代码

val dateFirst = "20 Aug 2012"
val dateSecond = "12/16/2020 12:00:00 AM"

val dateFirstConverted = LocalDate.parse(dateFirst, DateTimeFormatter.BASIC_ISO_DATE)
val dateSecondConverted = LocalDate.parse(dateSecond, DateTimeFormatter.BASIC_ISO_DATE)

println(dateFirstConverted)
println(dateSecondConverted)
Run Code Online (Sandbox Code Playgroud)

然后我得到这样的错误。

Exception in thread "main" java.time.format.DateTimeParseException: Text '20 Aug 2012' could not be parsed at index 0
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDate.parse(LocalDate.java:400)
    at App.TryKt.main(try.kt:11)
    at App.TryKt.main(try.kt)
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决这个问题吗?

小智 7

您遇到问题是因为不支持日期格式,我邀请您阅读这篇文章https://www.claudebueno.com/programmation/comment-gerer-la-date-et-lheure-avec-kotlin.htm但是在您的情况下,如果您希望代码运行,请更改 的格式date,如下所示:

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

fun main() {
    //example
    val current = LocalDateTime.now()
    val formatter = DateTimeFormatter.BASIC_ISO_DATE
    val formatted = current.format(formatter)
    println("Current Date is: $formatted")
    
    //your code
    val dates = /*"20 Aug 2012"*/ "20120820"
    val datess = LocalDate.parse(dates, DateTimeFormatter.BASIC_ISO_DATE)
    println(datess)
}
Run Code Online (Sandbox Code Playgroud)