0

I was handed a Java Spring Boot application and I only need to change one thing. Among other data in the json data I handle, I have the following:

"valueSetAt":{
   "dateTime":{
      "date":{
         "year":2023,
         "month":5,
         "day":2
      },
      "time":{
         "hour":13,
         "minute":1,
         "second":36,
         "nano":335000000
      }
   },
   "offset":{
      "totalSeconds":0
   },
   "zone":{
      "id":"UTC"
   }
}

I need to convert this form of date and time to datetime of the format

"startTime":
   "2023-03-31T13:00:00.000Z"

The problem is, I can't do anything before the transformation because this wrong format is coming from an API to which I can't see or change anything. The developers from the API said that the transfomation occured when they processed the data to json. Essentialy I think that what I need is to above date and time to convert from ZonedDateTime to a String?

LinFelix
  • 1,026
  • 1
  • 13
  • 23
adamkwn
  • 49
  • 9
  • Search for Jackson JavaTimeModule. – Ole V.V. May 23 '23 at 10:26
  • Yeah thank you very much, I'm trying that way. But with JavaTimeModule, how can I convert the above mentioned dateTime into a string? – adamkwn May 23 '23 at 11:07
  • 1
    Is it that you have some json (a String) with a field "valueSetAt" and you want to replace that with a "startTime" field (each with data as you have shown)? – Bohemian May 23 '23 at 16:11

1 Answers1

0

Seems there're already answer for your question.

It's not clear whether you're consumer or producer of those values, but on case of both, you can handle it by specifiyng getter and setter with appropriate annotations on it:

public class DtoObject {
  private ZonedDateTime dateTimeField;

  // Used during serialization
  @JsonProperty("startTime")
  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
  public ZonedDateTime getStartTime() {
    return dateTimeField;
  }

  // Used during deserialization
  // eg. @JsonFormat(pattern = "yyyy-MM-dd") 
  public void setDateTimeField(ZonedDateTime dateTimeField) {
    this.dateTimeField = dateTimeField;
  }
}
  • I am neither of those. I am using an API and receive these data. Then I'm processing them and send them in a different format. My problem is that I can't convert the above json into a datetime string (as I mention). – adamkwn May 23 '23 at 10:56
  • If you're using API, process somethins, and then send, then it means you're consuming others api and produce your own api. Solutions at the provided link and provided code should help you – Irremediable May 23 '23 at 11:20