MnTanProject
MnTanProject

Reputation: 33

Mongodb java driver automatically convert date to local machine timezone when read using aggregate

Date stored in the database as utc timezone. But when retrieved it from the database using aggregate it automatically converts to my local machine timezone. Is this because of the Mongodb java driver? For example i stored: a document ---

{"_id":"5d72010ef608c30a0b33be8f","salesDate":"2019-09-06T06:47:42.184Z"}

when read using MongoDb compass it displayed the salesDate same as above, but when retrieved using mongodb java driver:

MongoCollection<Document> collectionDoc = database.getCollection(this.collectionName);
AggregateIterable<Document> output = collectionDoc.aggregate(agg);

for (Document document : output) {
    System.out.println("document: " + document);
}


note that no conversion was made, but when printed the output to console using for loop it displays salesDate with my local machine timezone.

document: Document{{_id=5d72010ef608c30a0b33be8f, salesDate=Fri Sep 06 13:47:42 ICT 2019}}

I am using MongoDB java driver version 3.11.0-beta4, java 8. any ideas anyone? is it the driver automatically convert to local machine timezone or it Java using os timezone?

Upvotes: 0

Views: 1569

Answers (1)

Sohan
Sohan

Reputation: 6809

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, setting my timezone as UTC from within the code itself something like this,

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

If you only want to set the default timezone for joda time, use DateTimeZone.setDefault.

Upvotes: 1

Related Questions