1

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)
João Dias
  • 16,277
  • 6
  • 33
  • 45
Rafael Souza
  • 1,143
  • 2
  • 13
  • 29
  • What error does the function produce? – esQmo_ Nov 19 '21 at 23:19
  • update the question with the beginning of the error – Rafael Souza Nov 19 '21 at 23:25
  • Your formatter is configured to parse _dates_, but it looks like the `String` passed to the function is a _date & time_. The date part of the `String` is also not in the format you seem to expect (year-month-day vs. year/month/day). – Slaw Nov 19 '21 at 23:29
  • If the date is in ISO format (YYYY-MM-DDTHH:MM:SS.SSSZ), why are you trying to parse it in dd/MM/yyyy format? – gidds Nov 19 '21 at 23:29
  • Well, the date passed to the function doesn't seem correct: Unparseable date: "2021-11-18T23:39:45.000Z" – esQmo_ Nov 19 '21 at 23:29

1 Answers1

2

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

João Dias
  • 16,277
  • 6
  • 33
  • 45
  • 1
    I used this solution 'implementation "com.jakewharton.threetenabp:threetenabp:1.2.1"' because my minimum version is 21 I saw the solution in this [post](https://stackoverflow.com/questions/56695997/how-to-fix-call-requires-api-level-26-current-min-is-25-error-in-android/56696502) thank you very much – Rafael Souza Nov 19 '21 at 23:59