Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format the json date format using spring boot

I am working on spring boot and gradle for creating a rest service. Now I need to format the json date in the form of "yyyy-MM-dd", i.e, the format should be dateOfBirth: "16-03-2015", but I am getting "dateOfBirth: -751181400000". I added the below piece of code in my Apllication.java class, but still not able to get the desired output.

@Bean
@ConditionalOnClass({ ObjectMapper.class, Jackson2ObjectMapperBuilder.class })
public Jackson2ObjectMapperBuilder jacksonBuilder()
{ 
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); 
    builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd")); 
    return builder; 
}

And Application.java:

@Configuration
@Import(SubjectServiceConfig.class)
@EnableAutoConfiguration
@EnableEurekaClient
@ComponentScan({"com.billing"})
@EnableWebMvc
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
public class Application {
public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}
}

Kindly help me out in resolving this issue.

like image 369
Pramod Avatar asked Mar 16 '15 13:03

Pramod


People also ask

How do I set date format in JSON?

There is no date format in JSON, there's only strings a de-/serializer decides to map to date values. However, JavaScript built-in JSON object and ISO8601 contains all the information to be understand by human and computer and does not relies on the beginning of the computer era (1970-1-1).

Does JSON support date format?

JSON does not directly support the date format and it stores it as String. However, as you have learned by now that mongo shell is a JavaScript interpreter and so in order to represent dates in JavaScript, JSON uses a specific string format ISODate to encode dates as string.

What is @JsonFormat in spring boot?

@JsonFormat is a Jackson annotation that we use to specify how to format fields and/or properties for JSON output. Specifically, this annotation allows us to specify how to format Date and Calendar values according to a SimpleDateFormat format.

How are dates represented in JSON?

JSON format does not have a special type for dates. So dates have to be represented in JSONs as numbers of milliseconds or as strings. If dates are formatted as strings, the developer can read them.


1 Answers

With Spring Boot, you should be able to set the default way that Jackson formats dates by setting the following property in your application.yml/application.properties:

spring.jackson.date-format= # Date format string (e.g. yyyy-MM-dd HH:mm:ss), or a fully-qualified date format class name (e.g. com.fasterxml.jackson.databind.util.ISO8601DateFormat)
like image 105
adam p Avatar answered Oct 01 '22 11:10

adam p