I'm having a small problem with formatting a Java 8 LocalDateTime in my Spring Boot Application. With 'normal' dates I have no problem, but the LocalDateTime fields are converted to the following:
"startDate" : {
"year" : 2010,
"month" : "JANUARY",
"dayOfMonth" : 1,
"dayOfWeek" : "FRIDAY",
"dayOfYear" : 1,
"monthValue" : 1,
"hour" : 2,
"minute" : 2,
"second" : 0,
"nano" : 0,
"chronology" : {
"id" : "ISO",
"calendarType" : "iso8601"
}
}
While I would like convert it to something like:
"startDate": "2015-01-01"
My code looks like this:
@JsonFormat(pattern="yyyy-MM-dd")
@DateTimeFormat(iso = DateTimeFormat.ISO.TIME)
public LocalDateTime getStartDate() {
return startDate;
}
But either of the above annotations don't work, the date keeps getting formatted like above. Suggestions welcome!
Writing this answer as a reminder for me as well.
I combined several answers here and in the end mine worked with something like these. (I am using SpringBoot 1.5.7 and Lombok 1.16.16)
@JsonDeserialize(using= LocalDateDeserializer.class)
does not work for me with the below dependency.I have used the below code converter to deserialize the date into a
java.sql.Date
.update: Spring Boot 2.x doesn't require this configuration anymore. I've hopefully given a more up to date answer here: https://stackoverflow.com/a/53848020/323221
(This is the way of doing it before Spring Boot 2.x, it might be useful for people working on an older version of Spring Boot)
I finally found here how to do it. To fix it, I needed another dependency:
By including this dependency, Spring will automatically register a converter for it, as described here. After that, you need to add the following to application.properties:
This will ensure that a correct converter is used, and dates will be printed in the format of
2016-03-16T13:56:39.492
Annotations are only needed in case you want to change the date format.
This work fine:
Add the dependency:
Add the annotation:
Now, you must get the correct format.
To use object mapper, you need register the JavaTime
As already mentioned, spring-boot will fetch all you need (for both web and webflux starter).
But what's even better - you don't need to register any modules yourself. Take a look here. Since
@SpringBootApplication
uses@EnableAutoConfiguration
under the hood, it meansJacksonAutoConfiguration
will be added to the context automatically. Now, if you look insideJacksonAutoConfiguration
, you will see:This fella will be called in the process of initialization and will fetch all the modules it can find in the classpath. (I use Spring Boot 2.1)
Here it is in maven, with the property so you can survive between spring boot upgrades