1

I need to read in some json, sort it, then output it again. I am using this to de-seralise and serialise the json:

    private static Gson gson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
        .create();

If I parse this to a Date:

"activedDate": "2021-04-20T21:48:04.107Z",

Then output it again as Json, I get this:

"activedDate": "2021-04-20T21:48:04.107+0000",

But I need it to have Z instead of +0000 if possible.

Is this possible (without hacking the resultant strings)?

I am forcing my laptop to UTC thusly:

java -Duser.timezone=UTC  -jar my.jar
John Little
  • 10,707
  • 19
  • 86
  • 158
  • Set the format to `..SSS'Z'`? – Kayaman May 24 '21 at 21:28
  • 1
    My assumption is that this would add a static char "Z" regardless of the timezone? If the timezone happened to be +1000, then it should not show Z in this case... – John Little May 25 '21 at 11:10
  • See https://stackoverflow.com/q/8405087/2541560 and https://stackoverflow.com/q/7556851/2541560 – Kayaman May 25 '21 at 14:21
  • 1
    Thanks, but those two are both for the de-serialisation, which works fine. Its the serialization which is not working as desired. – John Little May 25 '21 at 14:48
  • That's completely irrelevant since your issue is with date formatting. – Kayaman May 25 '21 at 17:52
  • Date formatting works fine in de-serialiseation: I can read Z ok. I just cant get gson to write it. Those posts do not address this unfortunately. – John Little May 26 '21 at 08:25
  • Unfortunately for you, I guess. Many people can get a lot of information out of them. You're not making a lot of effort to solve your own problem, are you? – Kayaman May 26 '21 at 08:34

1 Answers1

0

Yes, use X. From the DateTimeFormatter docs:

   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;

So a format string like yyyy-MM-dd'T'HH:mm:ss.SSSX will give you a date like 2022-07-26T16:46:35.247Z.

Steve Kehlet
  • 6,156
  • 5
  • 39
  • 40