I have Service
fetch date string from web and then I want to pare it to Date
object. But somehow application crashes.
This is my string that I\'m parsi
Since Z and XXX are different, I've implemented the following workaround:
// This is a workaround from Z to XXX timezone format
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") {
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
StringBuffer rfcFormat = super.format(date, toAppendTo, pos);
return rfcFormat.insert(rfcFormat.length() - 2, ":");
}
@Override
public Date parse(String text, ParsePosition pos) {
if (text.length() > 3) {
text = text.substring(0, text.length() - 3) + text.substring(text.length() - 2);
}
return super.parse(text, pos);
}
}
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).
Android SimpleDateFormat is different from Java 7 SDK and does not support 'X' to parse ISO 8601. You can use the 'Z' or 'ZZZZZ' styles to format and programatically set the time zone to UTC. Here is a util class:
public class DateUtil {
public static final String iso8601DatePattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ";
public static final DateFormat iso8601DateFormat = new SimpleDateFormat(iso8601DatePattern);
public static final TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
static {
iso8601DateFormat.setTimeZone(utcTimeZone);
}
public static String formatAsIso8601(Date date) {
return iso8601DateFormat.format(date);
}
}
Simple solution:
Use this yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ
Instead of yyyy-MM-dd'T'HH:mm:ss.SSSXXX
Done.
according to android documentation zone offset with X
format is supporting in API level 24+
Letter Date or Time Component Supported (API Levels) X Time zone 24+
so we can't use for lower APIs, I found a workaround for this issue:
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(date).let {
StringBuilder(it).insert(it.length - 2, ":").toString()
}
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.