在mongo DB中存储java 8 LocalDate

编程入门 行业动态 更新时间:2024-10-26 16:29:13
本文介绍了在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 属性在保存到数据库之前被转换为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

本文发布于:2023-11-16 06:17:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1601746.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:DB   mongo   LocalDate   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!