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

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

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.

原文链接:Use ZonedDateTime in Spring WebFlux (MongoDB Reactive)

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容