您的位置:首页 > 数据库 > Mongodb

JAVA 处理 Spring data mongodb 时区问题

2017-11-09 10:54 686 查看
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"}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: