IllegalArgumentException Unknown pattern character 'x', when using SimpleDateFormat
代码如下:
```try { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX") .parse("2019-05-14T19:00:11+08:00");} catch (ParseException e) { e.printStackTrace();}```
在Android 8.0运行没问题,但在5.1及以下会抛“IllegalArgumentException Unknown pattern character 'x', when using SimpleDateFormat”,如此看来基本可以认为是版本兼容问题
首先我们查找文档对于格式化定义,之前文章[日期格式化YYYY日期错位](http://blog.520wa.com/2018/01/03/date-formate-YYYY-in-java/)中有提到Java中Date and Time Patterns,下面我们再看看Android中java.txt.SimpleDateFormat中的
Date and Time Patterns


从中我们看到X和Z都是time zone,改成Z即可。
Android中的SimpleDateFormat也是使用Java的api
Android 5.0开始采用了JDK 7,对应应该已经有X了(这里不可以加链接,自行前往java SimpleDateFormat查看)
但我们从Android 22的源码中可以看到
```public class SimpleDateFormat extends DateFormat { private static final long serialVersionUID = 4774881970558875024L; // 'L' and 'c' are ICU-compatible extensions for stand-alone month and stand-alone weekday. static final String PATTERN_CHARS = "GyMdkHmsSEDFwWahKzZLc"; // The index of 'Z' in the PATTERN_CHARS string. This pattern character is supported by the RI, // but has no corresponding public constant. private static final int RFC_822_TIMEZONE_FIELD = 18; // The index of 'L' (cf. 'M') in the PATTERN_CHARS string. This is an ICU-compatible extension // necessary for correct localization in various languages (http://b/2633414). private static final int STAND_ALONE_MONTH_FIELD = 19; // The index of 'c' (cf. 'E') in the PATTERN_CHARS string. This is an ICU-compatible extension // necessary for correct localization in various languages (http://b/2633414). private static final int STAND_ALONE_DAY_OF_WEEK_FIELD = 20; private String pattern; private DateFormatSymbols formatData;```
Android 28
```public class DateFormatSymbols implements Serializable, Cloneable {... /** * Unlocalized date-time pattern characters. For example: 'y', 'd', etc. * All locales use the same these unlocalized pattern characters. */ // Android-changed: Add 'c' (standalone day of week), 'b' (day period), // 'B' (flexible day period) static final String patternChars = "GyMdkHmsSEDFwWahKzZYuXLcbB";```
重点:
static final String PATTERN_CHARS = "GyMdkHmsSEDFwWahKzZLc";
static final String patternChars = "GyMdkHmsSEDFwWahKzZYuXLcbB";
源码里可以看到导致问题原因,但是为何Android 22中的java代码与Java 7中不一致呢?
--- END ---
分享程序员所看、所想、所悟、所望
