LoginSignup
0
0

More than 1 year has passed since last update.

gsonでパースするときに DateTimeParseException になったメモ

Last updated at Posted at 2021-08-26

gson で 日付をパースするときに原因不明のエラーになってハマりました

java.time.format.DateTimeParseException: 
Text '2021-01-11T09:59:01' could not be parsed at index 19

もともと swagger から自動生成したコードで、
org.threeten.bp.OffsetDateTime が使われていたので、 java.time.OffsetDateTime に変更してもエラーは変わらず。

java.time.LocalDateTime に変更してもエラーは変わらず。

散々ハマってしまったけど、解決方法は下記でした
gson に設定する LocalDateTimeTypeAdapter の formatter の指定が下記になっていた

DateTimeFormatter.ISO_OFFSET_DATE_TIME

これを下記にしたら無事にパースできました

DateTimeFormatter.ISO_LOCAL_DATE_TIME

上記は、java.time.OffsetDateTime に変更している前提です。
OffsetDateTime のままだとやはりパースできず下記エラーになります。(オフセット部分がないので)

Unable to obtain ZoneOffset from TemporalAccessor:
 {},ISO resolved to 2021-08-27T16:10:23 of type java.time.format.Parsed

threeten.bp パッケージ (ThreeTen Backport) は DateTime の機能をJava 6でも使えるように移植したものなので、今となっては使う必要性はないと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0