MongoDb BSON stores Date in UTC time

﹥>﹥吖頭↗ 提交于 2020-04-10 02:54:10

问题


If I try to put a date field in a Document (BSON) and write it to Mongo, BSON writes it in UTC. For example, a date

DateTime dateTime = new DateTime("2015-07-01");
Document doc = new Document("date", dateTime.toDate());

will be stored as

"date" : ISODate("2015-06-30T18:30:00Z")

in Mongo. And, if I retrieve it using the same Java Driver I get it as

Wed Jul 01 00:00:00 IST 2015

Great. Is there no solution to this? I mean, why can't I store my date as I want it? What If I need to query on the DB from another time zone? I will be getting different results? Date field is an important part of Mongo with a rich set of operators wrapped around it. Still, why doesn't Mongo provide this flexibility? Thanks


回答1:


IMO, mongo did everything right. You instantiate date using your local timezone and then store it in mongo in UTC. And then when you ask mongo to retrieve it for you it shifts date to your local timezone again.

If you dont want to deal with timezone shifting, just set your local timezone to UTC using the following flag:

-Duser.timezone="UTC"



回答2:


When using DateTime (from org.joda.time or java.time) a date with time zone is created and MongoDB has unfortunately no support for it. (see BSON Types)

Therefore persisting it in UTC is a easy and reliable solution without loosing any data.

As a alternative you should take a look at LocalDateTime. It contains no DateTimeZone and so nothing has to be converted first.




回答3:


I have the problem solved by setting my timezone as UTC from within the code itself.

    DateTimeZone zone = DateTimeZone.UTC;
    DateTimeZone.setDefault(zone);



回答4:


Got a very simple solution. Let the date be in UTC in your MongoDB.
Whenever you fetch it to your UI, just do:

new Date(fetchedDate);

It converts it to the local date.



来源:https://stackoverflow.com/questions/31654567/mongodb-bson-stores-date-in-utc-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!