Android parse String to Date - unknown pattern character 'X'
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.
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
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).