- • Quickstart
- • Documentation
- • Documentation DevOps
- • Next Steps
- • Spring Boot
- • Spring Data
- › Spring Data MongoDB
- • Spring Security
- • Frontend
- • Multi-Module
Last updated: 2022-03-20
Using OffsetDateTime with Spring Boot and MongoDB
Did you know that you can save days or weeks of development time when starting new Spring Boot apps? br With Bootify you have the right helper at your side - get a runnable prototype in minutes and focus on your business logic instead. Best practices included.
MongoDB natively supports
Date as a field type, but here only a time is stored without time zone or offset. Using a converter we can support
OffsetDateTime directly in our Spring Boot application and persist it as a custom type with date and offset.
If we save a document with an
OffsetDateTime without a converter, we get the following error message.
In order to persist our date without loss and also restore it when reading from MongoDB, we store time and offset separately in a custom type. For this we need the following converters.
Converter for reading OffsetDateTime from MongoDB
Converter for writing OffsetDateTime to MongoDB
By providing a
MongoCustomConversions bean in our configuration, these are made available in the application context and automatically picked up by Spring Data MongoDB. So our original error message is gone and we can use
OffsetDateTime in our documents without worrying about their way of persistence! This approach can be adapted to work with
ZonedDateTime as well.
Providing the converters in our config
Using Bootify, a Spring Boot application for MongoDB can be generated in the Free plan without registration, including the documents, fields and relations. The converters are also pre-configured if at least one field is to be persisted with
OffsetDateTime. In the Professional plan, Mongock is available to create collections together with a JSON schema for basic validation.
No registration required