在mongo DB中存储java 8 LocalDate [英] Storing java 8 LocalDate in mongo DB

查看:2198
本文介绍了在mongo DB中存储java 8 LocalDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Spring启动 1.5.4.RELEASE 和Mongo驱动程序 3.4.2

Using Spring boot 1.5.4.RELEASE and Mongo driver 3.4.2.

我想在 mongo DB 中存储 LocalDate ,但我面临一个奇怪的问题。

I want to store LocalDate in mongo DB, but I am facing a weird problem.

        LocalDate startDate = LocalDate.now();
        LocalDate endDate = LocalDate.of(2020,12,01);
        System.out.println("---- StartDate : ---"+startDate); 
        System.out.println("-----End Date : ----"+endDate);

        repository.save(new Person("Mehraj","Malik", startDate, endDate));




控制台上的输出:

Output on Console :

---- StartDate:--- 2017-08-26

---- StartDate : ---2017-08-26

-----结束日期:---- 2020-12- 01

-----End Date : ----2020-12-01

但在MongoDb中存储的日期不正确。

But In MongoDb it is storing incorrect dates.

以下是来自MongoDb的json:

Following is the json from MongoDb :


startDate:ISODate( 2017-08-25T18:30:00.000Z),

"startDate" : ISODate("2017-08-25T18:30:00.000Z"),

endDate:ISODate(2020-11-30T18:30:00.000Z)

"endDate" :ISODate("2020-11-30T18:30:00.000Z")

另外,我注意到根据印度时间,存储的时间也是不正确的。

Also, I have noticed that the stored time is also incorrect according to Indian time.

有人可以在这里帮助我..为什么日期在控制台上是正确的但在MongoDB中没有,以及如何解决这个问题。

Can someone please help me here.. Why the dates are correct on console but not in MongoDB and how to resolve this problem.

推荐答案

date object return as
java.util.Date

问题可能在于您保存 startDate endDate value,其 toString()方法可能会使用JVM的默认时区来更新值。

The problem could possibly be that while you save the startDate and the endDate value, its toString() method would probably use the JVM's default time zone to update the value.

此处 doc 声明 官方BSON规范将BSON日期类型称为UTC日期时间。 ,这可能是您的 LocalDateTime <的原因/ code>属性在保存到数据库之前被转换为UTC时区。

The doc here states that The official BSON specification refers to the BSON Date type as the UTC datetime. and that could be the reason your LocalDateTime attributes were converted to the UTC time zone prior to being saved to the DB.

同样为了避免这种混淆,建议使用bson类型 timestamp 更新日期字段。

Also to avoid such confusion would suggest using the bson type timestamp to update date fields.

这篇关于在mongo DB中存储java 8 LocalDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆