ZonedDateTime with MongoDB

后端 未结 2 766
一向
一向 2020-12-10 03:49

Trying to use ZonedDateTime with MongoDB. I\'m able to save ZonedDateTime in MongoDB but when i look at the record it has

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 04:29

    After spending way too much time debugging this, I finally found a working solution for latest version of spring boot / spring data. This is currently working for me on Spring Boot 2.0.0.M7.

    With the accepted answer from veeram, I was getting Couldn't find PersistentEntity for type

    I hope this helps someone avoid going down the rabbit hole.

    @Configuration
    public class MongoConfiguration {
    
        @Bean
        public MongoCustomConversions customConversions(){
            List> converters = new ArrayList<>();
            converters.add(DateToZonedDateTimeConverter.INSTANCE);
            converters.add( ZonedDateTimeToDateConverter.INSTANCE);
            return new MongoCustomConversions(converters);
        }
    
        enum DateToZonedDateTimeConverter implements Converter {
    
            INSTANCE;
    
            @Override
            public ZonedDateTime convert(Date source) {
                return ofInstant(source.toInstant(), systemDefault());
            }
        }
    
        enum ZonedDateTimeToDateConverter implements Converter {
    
            INSTANCE;
    
            @Override
            public Date convert(ZonedDateTime source) {
                return Date.from(source.toInstant());
            }
        }
    }
    

提交回复
热议问题