Store Java 8 Instant as BSON date using SpringData-MongoDB Store Java 8 Instant as BSON date using SpringData-MongoDB spring spring

Store Java 8 Instant as BSON date using SpringData-MongoDB


I think the problem is what you are trying to use Instant as a time. Conceptually it is a point of the timeline and it does not imply formatting.

As we know, Java 8 time API was developed with an eye at joda-time (and with partisipating of joda-time's developers). Here is comment from joda-time Instant:

An Instant should be used to represent a point in time irrespective of any other factor, such as chronology or time zone.

That's why there is no formatting possibilities for org.joda.time.Instant in JodaDateTimeFormatAnnotationFormatterFactory which appeared in Spring since version 3.0. And also it was not implemented in Jsr310DateTimeFormatAnnotationFormatterFactory

So, you should use custom converter or consider to use more suitable class.


I use instant for all timestamp type data, just like your timecreated. If it is for the end user, like a calendar entry, than LocalDateTime works better but they can all be created using ISO formatted time strings. At some point, the point of time data (date or instant) will need to be formatted for readability or serialization/portability.

So to answer this question if anyone runs into this issue with current MongoDB versions, you do not need to do anything in your code. I initialized some data in my mongodb container using the init script. I used ISODate formatting.

 "timestamp": ISODate("2020-03-17T13:50:56.618Z")

I also have a Spring Boot 2 and Spring Data application. The documentation has full support for it. https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping-conversion