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"}

 

转载于:https://www.cnblogs.com/sweetchildomine/p/7808314.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值