Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb BSON stores Date in UTC time

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

like image 492
void Avatar asked Jul 27 '15 13:07

void


1 Answers

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"
like image 135
SimY4 Avatar answered Oct 23 '22 21:10

SimY4