Skip to content

Instantly share code, notes, and snippets.

@jyemin
Created July 16, 2014 16:57
Show Gist options
  • Save jyemin/84ccac245782f1ebdc98 to your computer and use it in GitHub Desktop.
Save jyemin/84ccac245782f1ebdc98 to your computer and use it in GitHub Desktop.
An example showing how to integrate support for Joda DateTime into the MongoDB Java driver.
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import org.bson.BSON;
import org.bson.Transformer;
import org.joda.time.DateTime;
import java.net.UnknownHostException;
import java.util.Date;
/**
* An example showing how to integrate support for Joda DateTime into the MongoDB Java driver.
*/
public class MongoDBWithJodaExample {
public static void main(String[] args) throws UnknownHostException {
// Add hook to encode Joda DateTime as a java.util.Date
BSON.addEncodingHook(DateTime.class, new Transformer() {
@Override
public Object transform(final Object o) {
return new Date(((DateTime) o).getMillis());
}
});
// Add hook to decode java.util.Date as a Joda DateTime
BSON.addDecodingHook(Date.class, new Transformer() {
@Override
public Object transform(final Object o) {
return new DateTime(((Date) o).getTime());
}
});
MongoClient mongoClient = new MongoClient();
DBCollection c = mongoClient.getDB("test").getCollection("joda");
c.drop();
// insert a document containing a Joda DateTime
c.insert(new BasicDBObject("createdAt", new DateTime()));
DBObject doc = c.findOne();
// Note that when querying for this document, it will come back as a Joda DateTime as well.
System.out.println(doc.get("createdAt").getClass());
}
}
@thedarkdestructor
Copy link

Yeah, the timezone is lost in this way...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment