【发布时间】:2018-04-04 13:45:02
【问题描述】:
我试图告诉 Gson 如何解析 LocalDateTime 和 LocalDate,但我收到了这个错误,在我看来它应该与格式匹配。我在想要么是我不了解解析日期,要么是我不了解 Gson。
java.time.format.DateTimeParseException:无法在索引 0 处解析文本“2017101800000700”
Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
@Override
public LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
return LocalDateTime.parse(json.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
}
}).registerTypeAdapter(LocalDate.class, new JsonDeserializer<LocalDate>() {
@Override
public LocalDate deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
return LocalDate.parse(json.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern("yyyyMMdd"));
}
}).create();
【问题讨论】:
-
好吧 2017101800000700 不适合 yyyyMMddHHmmssSSS - 你没有足够的数字。 (日期后面是00000700,HHmmss为000007,SSS只剩下00。)
-
但我怀疑 0700 实际上是从 UTC 偏移的时区。
-
@JonSkeet 唯一奇怪的事情(如果 0700 是偏移量)是缺少
+或-符号,所以它是一个模棱两可的偏移量。还是没有标志就意味着积极? -
@Hugo:同意,这很奇怪。
标签: java gson java-time datetime-parsing localdate