0

I'm inserting a Date in a MongoDB key from Java as follows:

DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse("1-Apr-1970");

BasicDBObject doc = new BasicDBObject("name", "john").append("birthdate", date);

Querying for the Document, it results the following Date:

{ "_id" : { "$oid" : "55263cd3d3d584440534f0a4"} , "name" : "john" , 
"birthdate" : { "$date" : "1970-03-31T23:00:00.000Z"}}

As you can see, the month is not what I expected (04). Is there a better way to insert a Date in MongoDB from Java ? as it is, I find it pretty useless when I try to read it back from Java (I'd rather use a plain key String).

user2824073
  • 2,407
  • 10
  • 39
  • 73

1 Answers1

2

This happens because of the implementation of toString() method in BasicDbObject. By default dates are printed like that:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));

So you have time for GMT time zone. If you try to get date filed (e.g.: dbObject.get("birthdate")) you should be able to see expected value.

Piotr Chowaniec
  • 1,160
  • 12
  • 25