Date and mongodb

1,081 views
Skip to first unread message

andrea

unread,
Dec 27, 2011, 3:45:28 PM12/27/11
to mongodb-user
Hi everyone, i'm trying to insert a date (day/month,year) in mongodb
using java. I create the date using Calendar.getInstance(). Obviously
i can't insert the data on mongodb because mongo doesn't support the
tipe Calendar. So i think i have to cast it to turn it in to string,
but i can't do that!
Someone can help me?
Thanks!

andrea

unread,
Dec 27, 2011, 3:49:18 PM12/27/11
to mongodb-user
Hi everyone, i'm trying to insert a date (day/month,year) in mongodb
using java. I create the date in java using Calendar.getInstance().

Tyler Brock

unread,
Dec 27, 2011, 4:02:23 PM12/27/11
to mongodb-user
Use java.util.Date instead of the Calendar class.

Create a Date object like this:
Date now = new Date();

Dave it in a new object like this:
BasicDBObject time = new BasicDBObject("ts", now);
collection.save(time);

This is directly from the 10gen website:

http://www.mongodb.org/display/DOCS/Java+Types#JavaTypes-Dates%2FTimes

Good luck,

-Tyler

andrea

unread,
Dec 29, 2011, 6:08:29 AM12/29/11
to mongodb-user
Ok, perfect, but i have 2 more questions.
Firs if i don't whant to create the now date, but the 15/02/2012 date,
how can i do?
Second, it's possible to save on mongodb only the date and not all of
this (ISODate("2011-12-29T11:00:28.284z") )?
Thanks a lot and sorry for my not perfect english.

Scott Hernandez

unread,
Dec 29, 2011, 8:40:35 AM12/29/11
to mongod...@googlegroups.com
The mongodb Date type includes a time as well as the date (stored as
millisecs since epoch utc in 64bits). If you want to store something
other than that you could store an integer (32bit) for just the number
of days since epoch utc and do the conversion yourself when you
persist to and from mongodb.

Java has plenty of ways to construct a date from an arbitrary strings,
or other values:
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
or something like joda date/time

> --
> You received this message because you are subscribed to the Google Groups "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.
>

Reply all
Reply to author
Forward
0 new messages