java dates

425 views
Skip to first unread message

Tim Nelson

unread,
Oct 8, 2009, 1:47:47 PM10/8/09
to mongod...@googlegroups.com
It appears the java driver is inserting strings for dates. If I use javascript to enter a date it appears as ms from epoch, but if I use the java driver it appears as a string.

In javascript:

> db.coll.save({date: Date.parse("10/6/2009")})
> db.coll.find()
{"_id" :  ObjectId( "4ace1f27c510efab498a8a8d")  , "date" : 1254805200000}

In java(scala):

scala> val m = new Mongo
m: com.mongodb.Mongo = com.mongodb.Mongo@5319fe97

scala> val db = m.getDB("test")
db: com.mongodb.DB = test

scala> val d = new Date
d: java.util.Date = Thu Oct 08 12:29:37 CDT 2009

scala> db.getCollection("coll").save(new BasicDBObject("date", d))
res3: com.mongodb.DBObject = { "date" : "2009-10-08T17:29:37Z" , "_id" : "c7e19535bb21ce4a340eb600" , "_ns" : "coll"}

Back in js shell:

> db.coll.find()
{"_id" :  ObjectId( "c7e19535bb21ce4a340eb600")  , "date" : "Thu Oct 08 2009 12:29:37 GMT-0500 (CDT)"}

Is this the intended behavior or is it supposed to be using ms from epoch?

Thanks,
Tim


Eliot Horowitz

unread,
Oct 8, 2009, 2:30:05 PM10/8/09
to mongod...@googlegroups.com
This is a bit confusing, but what's happening is that res3 is call
toString on the object which gets output as json.
json doesn't have a date type, so its outputting as a string.
but the value stored in the db is the Date type which is milliseconds from epoc

so the output is misleading, but it should be storing correctly.

you can call .getClass() on "date" after a findOne() to prove it to yourself

Michael Dirolf

unread,
Oct 8, 2009, 2:33:41 PM10/8/09
to mongod...@googlegroups.com
Another problem is that Date.parse doesn't return a Date object, but
millis from epoch. To save as a Date from JS you should do:

new Date(Date.parse(...))

Dates in JS are confusing.

Tim Nelson

unread,
Oct 8, 2009, 2:54:06 PM10/8/09
to mongod...@googlegroups.com
So, if I understand correctly, Mongo stores dates as ms from epoch but it's not a regular integer, which is what my example js was inserting.

Thanks

Eliot Horowitz

unread,
Oct 8, 2009, 2:55:38 PM10/8/09
to mongod...@googlegroups.com
correct.

Mongo has a special Date type which is milliseconds from epoch.
in the shell, if you save a "new Date()" it will also save it as
milliseconds from epoch.

all the drivers are supposed to handle this automatically with the
native date types
Reply all
Reply to author
Forward
0 new messages