3

I am trying fetch some DateTime values stored in a local MySQL database in my Spring App. These dates are parsed into a ZoneDateTime and are then sent to a Client Front End as a json. I have an Object Mapper that specifies this conversion.

@Bean
public ObjectMapper objectMapper() {
    JavaTimeModule javaTimeModule = new JavaTimeModule();
    javaTimeModule.addSerializer(ZonedDateTime.class,
            new ZonedDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")));
    return Jackson2ObjectMapperBuilder.json().featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // ISODate
            .modules(javaTimeModule).build();
}

However, on the front-end, the values I receive are in Epoch time instead of the format specified in the ObjectMapper. I have checked the value parsed into ZoneDateTime and it is parsed correctly. My guess is that there is some fault in the process mapping the ZoneDateTime object into the json String value. What could be the fix of this?

Tabish Mir
  • 717
  • 6
  • 26
  • Is the epoch time correct? Don't know if it's really an issue, but does the `DateTime` from your database contain information about an offset or a zone or both? Your pattern `"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"` doesn't consider a zone, just an offset. – deHaar Jan 20 '20 at 11:54
  • @deHaar Yes the Epoch time is correct. The DateTime in the Database comes from a CreationTimestamp annotation over my Entity fields. – Tabish Mir Jan 20 '20 at 12:59

2 Answers2

3

Here is how to do it simply and efficiently:

@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="EEE MMM dd HH:mm:ss Z yyyy")
@JsonProperty("created_at") 
ZonedDateTime created_at;

This is a quote from a question: [Jackson deserialize date from Twitter to `ZonedDateTime` Also, I don't think that you need to add a special serializer for this. It works for me without this definition just fine.

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

https://docs.spring.io/spring/docs/4.3.0.RC1_to_4.3.0.RC2/Spring%20Framework%204.3.0.RC2/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.html#timeZone-java.lang.String- Docs says there is a timezone(String) method to override default timezone. I suppose you could pass the timezone into this method while building the ObjectMapper

@Bean
public Jackson2ObjectMapperBuilderCustomizer init() {
    return new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder builder) {
            builder.timeZone(TimeZone.getDefault());
        }
    };
}

You could use above code to override default timezone.

 return Jackson2ObjectMapperBuilder.json().featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // ISODate
            .modules(javaTimeModule).timeZone(TimeZone.getDefault()).build();

You could try this.

NaveenBharadwaj
  • 1,212
  • 5
  • 19
  • 42