Search code examples
androiddateparseexception

java.text.ParseException: Unparseable date: "1 Sep, 2022"


In my android app, I am using following code to convert date in other format. But it is not working.

var format = SimpleDateFormat("dd MMM, yyyy")
var date2 = format.parse("1 Sep, 2022")

It is working in most of cases but in few device got crash.

STACK_TRACE=java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:581)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
    ... 1 more  
Caused by: java.text.ParseException: Unparseable date: "1 Sep, 2022"
    at java.text.DateFormat.parse(DateFormat.java:389)
    at com.swastika.trading.Utils.AppConfig$Companion$insertScripToDabase$1.onResponse(AppConfig.kt:1167)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:226)
    at android.os.Looper.loop(Looper.java:313)
    at android.app.ActivityThread.main(ActivityThread.java:8669)
    ... 3 more

Solution

  • var format = SimpleDateFormat("dd MMM, yyyy", Locale.EN)
    var date2 = format.parse("1 Sep, 2022")
    

    You need to specify the language because of that "Sep". Otherwise September might be called something funny or abbreviated differently.

    (The new date time API would have been a more regular choice.)