Using Spring boot 1.5.4.RELEASE and Mongo driver 3.4.2.

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

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

But In MongoDb it is storing incorrect dates.

Following is the json from MongoDb :

"startDate" : ISODate("2017-08-25T18: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.

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

解决方案

The mongo-java client for a date object returns as instance of

java.util.Date.

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.

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.

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

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐