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"
}
Why are milliseconds being included in the formatted dates?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With