DEV Community

Thanaphoom Babparn
Thanaphoom Babparn

Posted on • Updated on

Use ZonedDateTime in Spring WebFlux (MongoDB Reactive)

Hello everyone. For this article we will be empowering our Spring WebFlux and MongoDB to be able to use ZonedDateTime, so let's get started.

TL;DR

You can find source code in this repository

Create Spring WebFlux Project

Alt Text

And if you want to implement ZonedDateTime inside our Spring WebFlux application, you can add ReadingConverter & WritingConverter for our MongoDB. you can see the code that implementation in the below.

@Configuration
public class MongoConfig {

    @Bean
    public MongoCustomConversions mongoCustomConversions() {
        List<Converter<?,?>> converters = new ArrayList<>();
        converters.add(ZonedDateTimeToDate.INSTANCE);
        converters.add(DateToZonedDateTime.INSTANCE);
        return new MongoCustomConversions(converters);
    }

    @ReadingConverter
    enum DateToZonedDateTime implements Converter<Date, ZonedDateTime> {

        INSTANCE;

        @Override
        public ZonedDateTime convert(Date date) {
            return date.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .truncatedTo(ChronoUnit.MILLIS);
        }
    }

    @WritingConverter
    enum ZonedDateTimeToDate implements Converter<ZonedDateTime, Date> {

        INSTANCE;

        @Override
        public Date convert(ZonedDateTime zonedDateTime) {
            return Date.from(zonedDateTime.toInstant());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

That's it. You can use ZonedDateTime as a datetime type in our class. 😁

Example of POST request

curl --location --request POST 'http://localhost:8080/promotions' \
--header 'Content-Type: application/json' \
--data-raw '{
    "name": "promotion-2",
    "startDate": "2021-06-01T10:00:00.000+07:00",
    "endDate": "2021-06-20T18:00:00.000+07:00"
}'
Enter fullscreen mode Exit fullscreen mode

Result

Alt Text

Alt Text

This is a short article on how to use the converter of ZonedDateTime in Spring Data MongoDB Reactive, I hope it will be useful for all readers.

Thank you very much. 😄

Top comments (0)