Dates as a concept are seamingly simple and straight forward. Though in programming world those could be rather complex starting from format, representation, time zones, machine default configuration going through different calendars and date manipulations.
In this post I won’t to give a quick tip on handling dates in an application that I am building. It will be short post, I promise.
What’s the problem
We are building an API that is written in Java and running inside Spring Boot container on Tomcat server. The application has single endpoint that allows us to do CRUD operations on a single entity, a Contact. All of the operations are annotated by Swagger annotation for documentation purposes. We use Spring which by default uses Jackson for JSON de/serialisation.
With the Swagger annotations there is a separate module that generates a client that should consume the service data. In our case we have a PHP client generated from the Swagger spec. So far all sounds pretty good no issues.
We’ve connected the two applications teh client and the service but there was a problem on the client side with Date’s format. It was receiving a epoch timestamp when expecting a valid ISO8601 format or RFC3339. Reason being that our Java applicaton was storing dates in that format in ElasticSearch and the API was outputing them in same format unable to format them in expected format.
Update Jackson date configuration in Spring Boot style
It turned out that the culprit was in Jackson’s ObjectMapper and more specifically in the default Date format, it’s set to use timestamps by default. There were few different ways to configure that but I decided to extend the default Spring Boot web component and update the serialiser.
What the code above is doing is pretty straight forward. We extends the WebMvcConfigurerAdapter that allows us to set the configuration properties for the MessageConverters in Spring Boot. We find the one that we’re interested in MappingJackson2HttpMessageConverter from there all we have to do is disable following property SerializationFeature.WRITE_DATES_AS_TIMESTAMPS and from now on all dates will be persisted and outputted in ISO8601 format e.g. yyyy-mm-dd’T’HH:mm:ssZZ and that’s all.
Use custom Date format
Let’s imagine that we want some other date format which is not standard. That’s all fine all you have to do is set the date format the following way:
Hope that helps someone out there! Sharing is caring, so please share 😉