Kotlin - SimpleDateFormat parsing takes infinite time

Viewed 11493

I am trying to parse date string with SimpleDateFormat which never stops nor gives any exception. Please see the code below,

fun getDate(dateStr: String) {

    try {
        /** DEBUG dateStr = '2006-04-16T04:00:00Z' **/
        val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH)
        val mDate = formatter.parse(dateStr) // this never ends while debugging
    } catch (e: Exception){
        Logger.e("Error $e") // this never gets called either
    }
}

What can be the possible issue?

Note: I am using,

Android Studio: 3.4.1, Kotlin version: 1.3.31, Min SDK: 23, Target SDK: 28, Compile SDK: 28

4 Answers

Use below function

fun getDate(dateStr: String) {
        try {
            /** DEBUG dateStr = '2006-04-16T04:00:00Z' **/
            val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH)
            val mDate = formatter.parse(dateStr) // this never ends while debugging
            Log.e("mDate", mDate.toString())
        } catch (e: Exception){
            Log.e("mDate",e.toString()) // this never gets called either
        }
    }

Your date format is incorrect. It should be as shown below

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

Notice the enclosing ' with Z. You are missing that in your date format.

I had a similar issue and my problem was that I was importing the wrong ParseException. You need to make sure you are importing the java.text parse exception.

Check the import code at the top of your file.

CORRECT ParseException

import java.text.ParseException

INCORRECT ParseException

import android.net.ParseException //Android example

Your date formats weren't lining up either, so of course that also needed to be fixed. But ideally you want the try/catch block to stop your program from crashing if the date strings are ever bad, so it's a good idea to test it with bad data.

Related