Skip to content

Instantly share code, notes, and snippets.

@jlecour
Created May 18, 2011 09:55
Show Gist options
  • Save jlecour/978307 to your computer and use it in GitHub Desktop.
Save jlecour/978307 to your computer and use it in GitHub Desktop.
How MongoDB (Ruby driver) handle Date/DateTime/Time
>> 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')
@jlecour
Copy link
Author

jlecour commented May 18, 2011

What if I want to store a Date in a document ?

@jlecour
Copy link
Author

jlecour commented May 18, 2011

It seems that I have to convert DateTime and Date values to Time (preferably in UTC) before storing them in MongoDB

@thbar
Copy link

thbar commented May 18, 2011

You have to store a UTC Time as advised.

See the MongoMapper date source as an example on how to do it.

@StephenOTT
Copy link

Super annoying that this issue still exists!!

@StephenOTT
Copy link

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

@glpunk
Copy link

glpunk commented Dec 13, 2013

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