Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android parse String to Date - unknown pattern character 'X'

The Android version of SimpleDateFormat doesn't support the X pattern so XXX won't work but instead you can use ZZZZZ which does the same and outputs the timezone in format +02:00 (or -02:00 depending on the local timezone).


Remove "XXX" from

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");

and everything would work fine.

Go through the list of symbols that can be used inside a SimpleDateFormat constructor. Although the documentation shows the "XXX" format, this doesn't work on Android and will throw an IllegalArgumentException.

Probably you are looking for "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

Change your code to

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); 

or

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); // if timezone is required

No one has mentioned about this error occurring on pre-nougat devices so I thought to share my answer and maybe it is helpful for those who reached this thread because of it.

This answer rightly mentions that "X" is supported only for Nougat+ devices. I still see that documentation suggests to use "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" and not sure why they don't make this point explicit.

For me, yyyy-MM-dd'T'HH:mm:ssXXX was working fine until I tried to test it on 6.0 device and it started crashing which led me to research on this topic. Replacing it with yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ has resolved the issue and works on all 5.0+ devices.


You are using the wrong date formatter.

Use this instead: DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

I think that android in contrast with Java 7 uses Z (as in Java 6) for timezones and not X. So, use this for your date formats.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!