I am working on spring boot for creating a REST application. And I have a DTO as shown below:
public class Subject {
private String uid;
private String number;
private String initials;
private Date dateOfBirth;
And I use Spring-Hateos and the reurn type of my controller is ResponseEntity<Resources<Resource<Subject>>>
. I need the date to be displayed in the "yyyy-mm-dd" format.
Starting from Spring Boot version 1.2.0.RELEASE , there is a property you can add to your
application.properties
to set a default date format to all of your classesspring.jackson.date-format
.For your date format example, you would add this line to your properties file:
Reference https://docs.spring.io/spring-boot/docs/1.2.0.RELEASE/reference/html/common-application-properties.html
If you have Jackson integeration with your application to serialize your bean to JSON format, then you can use Jackson anotation @JsonFormat to format your date to specified format.
In your case if you need your date into
yyyy-MM-dd
format you need to specify@JsonFormat
above your field on which you want to apply this format.For Example :
From Docs :
More Reference Doc
Hope this helps.
If you want to change the format for all dates you can add a builder customizer. Here is an example of a bean that converts dates to ISO 8601:
You most likely mean "yyyy-MM-dd" small latter 'm' would imply minutes section.
You should do two things
add
spring.jackson.serialization.write-dates-as-timestamps:false
in yourapplication.properties
this will disable converting dates to timestamps and instead use a ISO-8601 compliant formatYou can than customize the format by annotating the getter method of you
dateOfBirth
property with@JsonFormat(pattern="yyyy-MM-dd")