I am using the java 8 java.time.LocalDate to parse around dates.
But trying to insert a LocalDate object to mongodb. I get errors in the java driver:
Unfortunately, the MongoDB driver uses the java.util.Date
type, see the docs here
So you have to convert your LocalDate to a Date instance first, for example:
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("test");
DBCollection coll = db.getCollection("testcol");
LocalDate ld = LocalDate.now();
Instant instant = ld.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date date = Date.from(instant);
BasicDBObject doc = new BasicDBObject("localdate", date);
coll.insert(doc);
I would suggest using something like Morphia or Jongo to wrap the MongoDB driver though, as you can register global mappers to implicitly do these conversions on the fly, so that you can use LocalDate, etc, in your domain model