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.
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).
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.
@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.
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.
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)
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