MongoDb BSON stores Date in UTC time
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"
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.
I have the problem solved by setting my timezone as UTC from within the code itself.
DateTimeZone zone = DateTimeZone.UTC; DateTimeZone.setDefault(zone);