Gson: java.text.ParseException: Unparseable date: “2018-04-09T09:00:00+02:00”
如何解析格式的字符串日期:
1 | "2018-04-09T09:00:00+02:00" |
Gson使用:
1 |
但它给出了以下例外:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | com.google.gson.JsonSyntaxException: 2018-04-09T09:00:00+02:00 at com.google.gson.DefaultDateTypeAdapter.deserializeToDate(DefaultDateTypeAdapter.java:107) at com.google.gson.DefaultDateTypeAdapter.deserialize(DefaultDateTypeAdapter.java:82) at com.google.gson.DefaultDateTypeAdapter.deserialize(DefaultDateTypeAdapter.java:35) at com.google.gson.TreeTypeAdapter.read(TreeTypeAdapter.java:58) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:95) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:183) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:95) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:183) at com.google.gson.Gson.fromJson(Gson.java:805) at com.google.gson.Gson.fromJson(Gson.java:743) ... 35 more Caused by: java.text.ParseException: Unparseable date:"2018-04-09T09:00:00+02:00" at java.text.DateFormat.parse(DateFormat.java:337) at com.google.gson.DefaultDateTypeAdapter.deserializeToDate(DefaultDateTypeAdapter.java:105) ... 52 more |
提前致谢。
您将
Text can be quoted using single quotes (') to avoid interpretation
这意味着您的格式化程序期望字母
在同一个javadoc页面中,我们可以看到解析偏移的模式字母(
1 |
正如注释中所注意到的,模式
1 2 3 4 5 6 7 8 9 10 | String input ="2018-04-09T09:00:00+02:00"; Pattern pattern = Pattern.compile("(.*)([\\+|\\-]\\d{2}:\\d{2})"); Matcher matcher = pattern.matcher(input); if (matcher.find()) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); // timezone will be GMT+02:00 sdf.setTimeZone(TimeZone.getTimeZone("GMT" + matcher.group(2))); // parse date without the offset part Date date = sdf.parse(matcher.group(1)); } |
如评论中所述,您还可以使用三个后端:http://www.threeten.org/threetenbp/
这是java 8的日期/时间类的后端,它更好,更容易使用:
1 | OffsetDateTime odt = OffsetDateTime.parse("2018-04-09T09:00:00+02:00"); |
如果您仍然需要使用
1 |