MongoDB, Java: Retrieve date property as UTC

2020-05-01 07:41发布

I'm saving some entities to a Mongo database, these have Joda DateTime properties which have UTC set as a timezone. While saving works fine and I see the properties with correct values in the collection, once I retrieve the entities through Java the timezone gets set to UTC+2 again.

This is in the collection:

"created" : ISODate("2013-07-26T20:36:57.890Z")

I'm using Spring-Data-MongoDB to access the database.

Category category = mongoTemplate.findById(id, Category.class);

And I end up with this:

2013-07-26T23:05:56.439+02:00

Is there a way to tell Mongo do return the timezone stored in the date?

Hints appreciated, thank you!

1条回答
贪生不怕死
2楼-- · 2020-05-01 07:56

The driver is returning what the database has as a java.util.Date object. It knows nothing of the timezone that time represents. It does not store the Timezone anywhere. Mongo Shell always presents a time value as UTC.

That being said, if you want to work with it in your application code as UTC always, I think there is a way to tell the JODA library to do this: Defaulting date time zone to UTC for Jodatime's DateTime

查看更多
登录 后发表回答