1

I have a problem with DATE format and sending it (as an attribute from an entity named thesisDTO) via REST-Webservice (JSON).

enter image description here

I want to call a webservice method (POST-request) which excepts a DATE in the following format:

{   ...
"proposalDate":"Feb 17, 2022 7:50:09 AM" }

If I create a DATE variable with the following code, the method "toString()"gives me the right format:

Date currentDate = new Date();
IsyMNDLogger.getLogger().info("Date To String: "+currentDate.toString());

enter image description here

But if I add currentDate to my object thesisDTO with:

thesisDTO.setProposalDate(currentDate);

With the debugger I can see that the format is changed to: "Wed Feb 16 10:49:28 CET 2022" and my webservice request cannot read it.

enter image description here

Converting the thesisDTO to JSON and sending the request I do with the following code (javax.ws.rs):

Client restclient = ClientBuilder.newClient();
WebTarget target = restclient.target(url);
String response = target.request(MediaType.APPLICATION_JSON)
                .accept(MediaType.TEXT_PLAIN_TYPE)
                .post(Entity.json(thesisWebServiceDTO), String.class);

Has anyone an idea why the format is different and how I can change it? I can not use SimpleDateFormatter to change because that is only for displaying another format I think.

Thanks a lot, Nicole

Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • There is no "Date" data type in JSON. Use strings from the start, i.e. make `proposalDate` a `string`, make `setProposalDate()` expect a `string`, format the date the way you need it before setting it. – Tomalak Feb 17 '22 at 08:44
  • The "jax-rs" tag I added was a guess. If you're not using that, remove the tag and add a better one, please. – Tomalak Feb 17 '22 at 08:55

1 Answers1

1

First of all, Debugger displays date in whatever format its configured and has nothing to do with how you format your date. Date internally is stored as long value that holds the number of milliseconds since midnight of Jan 1, 1970 and and it doesn't hold any formatting info. If you format your date into a string and look at it in the debugger than you will see it exactly in the way you formatted your date. Now, for your issue, first of all please stop using class Date and even more so SimpleDateFormat they are definitely outdated (pun intended). Please look at java.time package and the classes that you should be using are DateTimeFormatter and TemporalAccessor interrface implementations such as ZonedDateTime, OffsetDateTime LocalDateTime or any other that might fit your needs. As for a date field in your DTO annotate it like this:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
ZonedDateTime proposalDate;

For more details look at the great answer for this question: Spring Data JPA - ZonedDateTime format for json serialization

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36