kotlinandroid-date

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


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

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)
}

Error:

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)

Solution

  • Parse your input to a ZonedDateTime and then apply a DateTimeFormatter to format it as you wish:

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

    Avoid using Java Date and consider using the new Java Date API (https://www.baeldung.com/java-8-date-time-intro).