JAVA 处理 Spring data mongodb 时区问题

Posted 高因咖啡

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA 处理 Spring data mongodb 时区问题相关的知识,希望对你有一定的参考价值。

Spring data mongodb 查询出结果的时候会自动 + 8小时,所以我们看起来结果是对的

但是我们查询的时候,并不会自动 + 8小时,需要自己处理

 

解决方法 1   @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") 

但是此注解,仅针对json 数据转换的时候处理,如果是form 提交 urlencoded 的时候就没办法了

    @Transient
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createDate;

虽然我们可以在 里面注册自定义的格式化,在进入Controller的时候 自动处理,但是 可能我们存在 mysql 跟 Mongodb 不同的 数据库,这种方式显然有些武断.

    @InitBinder
    public void initBinder(WebDataBinder binder)

解决方法 2 查询Mongodb 的时候,手动处理

 if (orderInfo.getCreateEndDate() != null && orderInfo.getCreateDate() != null)
            query.addCriteria(where("objectId").gte(new ObjectId(LocalDateTimeUtil.LocalDateTimeToUdate(orderInfo.getCreateDate().plusHours(8)))).lte(new ObjectId(LocalDateTimeUtil.LocalDateTimeToUdate(orderInfo.getCreateEndDate().plusHours(8)))));
        else {
            Optional.ofNullable(orderInfo.getCreateDate()).ifPresent(createDate -> query.addCriteria(where("objectId").gte(new ObjectId(LocalDateTimeUtil.LocalDateTimeToUdate(createDate.plusHours(8))))));
            Optional.ofNullable(orderInfo.getCreateEndDate()).ifPresent(endDate -> query.addCriteria(where("objectId").lte(new ObjectId(LocalDateTimeUtil.LocalDateTimeToUdate(endDate.plusHours(8))))));
        }

 

logback 打开debug 显示 Spring data mongodb 的查询语句,方便调试

    <Logger name="org.mongodb.driver" level="debug" />
    <logger name="org.springframework.data.mongodb.core.MongoTemplate" level="debug" />
{ "$gte" : { "$date" : "2017-11-01T00:00:00.000Z"}

 

以上是关于JAVA 处理 Spring data mongodb 时区问题的主要内容,如果未能解决你的问题,请参考以下文章

spring-data-mongo的MongoTemplate开发

spring 整合 mongo

spring data mongo使用@DBRef,怎么查询指定字段的集合

Morphia vs Spring Data Mongo

将 mongo 查询转换为 spring-data-mongo 查询

使用 spring data mongo 插入 Mongo 文档