JAVA 处理 Spring data mongodb 时区问题

时间:2021-02-16 01:45:50

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