Created
May 18, 2011 09:55
-
-
Save jlecour/978307 to your computer and use it in GitHub Desktop.
How MongoDB (Ruby driver) handle Date/DateTime/Time
This file contains hidden or 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
>> coll.insert({:date => Date.today}) | |
BSON::InvalidDocument: Date is not currently supported; use a UTC Time instance instead. | |
>> coll.insert({:date => DateTime.now}) | |
BSON::InvalidDocument: DateTime is not currently supported; use a UTC Time instance instead. | |
>> coll.insert({:date => Time.now}) #=> BSON::ObjectId('4dd39768b98f703261000003') |
It seems that I have to convert DateTime and Date values to Time (preferably in UTC) before storing them in MongoDB
You have to store a UTC Time as advised.
See the MongoMapper date source as an example on how to do it.
Super annoying that this issue still exists!!
Here is a way to deal with this issue:
def convertIssueDatesInMongo (issues)
issues.each do |y|
y["created_at"] = DateTime.strptime(y["created_at"], '%Y-%m-%dT%H:%M:%S%z').to_time.utc
y["updated_at"] = DateTime.strptime(y["updated_at"], '%Y-%m-%dT%H:%M:%S%z').to_time.utc
end
return issues
end
issues is a Array with a hash inside of it.
This example was from dealing with the Github API for the Issues API.
Note that "to_time" is only available starting in ruby ~1.9
Just more ideas to handle this, taking last post as reference, thanks
def parse_dates(obj)
obj.each do |key,value|
if key =~ /date/
date = obj[key].split('/')
date = "#{date[2]}-#{date[0]}-#{date[1]}T00:00:00+00:00"
obj[key] = DateTime.strptime(date, '%Y-%m-%dT%H:%M:%S%z').to_time.utc
end
end
end
a function to parse all elements into hash with word "date" in it key, ex: startdate, enddate, created_at_date, etc. Element with format mm/dd/yyyy
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What if I want to store a Date in a document ?