如何将日期从 yyyy/MM/dd 转换为 dd/MM/YYY 下面的函数会报错

How to convert date from yyyy/MM/dd to dd/MM/YYY the function below gives an error

如何将日期从 yyyy/MM/dd 转换为 dd/MM/YYY 下面的函数给出了一个错误

fun convertTime(date: String): String {
    val sdf = SimpleDateFormat("dd/MM/yyyy", Locale("pt", "BR"))
    sdf.isLenient = false

    val d: Date = sdf.parse(date)!!
    return sdf.format(d)
}

错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.quitanda, PID: 10526
    java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958) 
     Caused by: java.text.ParseException: Unparseable date: "2021-11-18T23:39:45.000Z"
        at java.text.DateFormat.parse(DateFormat.java:362)

将您的输入解析为 ZonedDateTime,然后应用 DateTimeFormatter 将其格式化为您希望的格式:

fun convertTime(date: String): String {
    val zonedDateTime = ZonedDateTime.parse(date)
    val dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale("pt", "BR"))

    return dtf.format(zonedDateTime)
}

避免使用 Java Date 并考虑使用新的 Java 日期 API (https://www.baeldung.com/java-8-date-time-intro).