Exclude milliseconds from date format (jackson + java 8 dates)

Daniel :

I am trying to figure out why jackson (2.9.5) formats dates from java 8 incorrectly.

data class Test(
        val zonedDateTim: ZonedDateTime = ZonedDateTime.now(),
        val offsetDateTim: OffsetDateTime = OffsetDateTime.now(),
        val date: Date = Date(),
        val localDateTime: LocalDateTime = LocalDateTime.now()
)

val mapper = ObjectMapper().apply {
    registerModule(KotlinModule())
    registerModule(JavaTimeModule())
    dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
    enable(SerializationFeature.INDENT_OUTPUT)
}

println(mapper.writeValueAsString(Test()))

From the date format I provided I would expect to get dates formatted without milliseconds but instead the result looks like this:

{
  "zonedDateTim" : "2018-07-27T13:18:26.452+02:00",
  "offsetDateTim" : "2018-07-27T13:18:26.452+02:00",
  "date" : "2018-07-27T13:18:26",
  "localDateTime" : "2018-07-27T13:18:26.452"
}

Any help is highly appreciated.

Best, Daniel

assylias :

dateFormat only applies to Date objects - the 3 other objects are handled by the JavaTimeModule, which uses ISO formatting by default.

If you want a different format, you can use:

val format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

val javaTimeModule = JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, LocalDateTimeSerializer(format));
javaTimeModule.addSerializer(ZonedDateTime.class, ZonedDateTimeSerializer(format));
mapper.registerModule(javaTimeModule);

You may also need to add mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); but I'm not 100% sure that it's necessary.

Also note that with that format, you will lose time zone and offset information. So you may want a different format for Offset/Zoned-DateTimes.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=75206&siteId=1