[java] Date format in the json output using spring boot

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.

This question is related to java rest spring-boot spring-hateoas

The answer is


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 :

public class Subject {

     private String uid;
     private String number;
     private String initials;

     @JsonFormat(pattern="yyyy-MM-dd")
     private Date dateOfBirth;  

     //Other Code  

}  

From Docs :

annotation used for configuring details of how values of properties are to be serialized.

More Reference Doc

Hope this helps.


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 your application.properties this will disable converting dates to timestamps and instead use a ISO-8601 compliant format

  • You can than customize the format by annotating the getter method of you dateOfBirth property with @JsonFormat(pattern="yyyy-MM-dd")


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 classes spring.jackson.date-format.

For your date format example, you would add this line to your properties file:

spring.jackson.date-format=yyyy-MM-dd

Reference https://docs.spring.io/spring-boot/docs/1.2.0.RELEASE/reference/html/common-application-properties.html


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:

@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
    return new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder builder) {
            builder.dateFormat(new ISO8601DateFormat());        
        }           
    };
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to spring-boot

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Why am I getting Unknown error in line 1 of pom.xml? Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured How to resolve Unable to load authentication plugin 'caching_sha2_password' issue ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName ERROR Source option 1.5 is no longer supported. Use 1.6 or later How to start up spring-boot application via command line? JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Examples related to spring-hateoas

Date format in the json output using spring boot