Created
July 16, 2014 16:57
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah, the timezone is lost in this way...