Skip to content

Instantly share code, notes, and snippets.

@orlando
Created December 8, 2011 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orlando/1447413 to your computer and use it in GitHub Desktop.
Save orlando/1447413 to your computer and use it in GitHub Desktop.
Date.to_mongo
class Date
def self.to_mongo(value)
if value.nil? || value == ''
nil
else
date = value.is_a?(::Date) || value.is_a?(::Time) ? value : ::Date.parse(value.to_s)
::Time.utc(date.year, date.month, date.day, date.try(:hour), date.try(:min), date.try(:sec))
end
rescue
nil
end
end
def test_Date_to_mongo_method
datetime = DateTime.new(2011,12,8,11,05,9) #Thu, 08 Dec 2011 11:05:09 +0000
date = "12/08/2011".to_date # Thu, 08 Dec 2011
assert_nil Date.to_mongo(nil) #passing nil
assert_nil Date.to_mongo('') # passing empty string
assert_nil Date.to_mongo('bla') #passing string
assert Date.to_mongo('12/08/2011').eql?(date.to_datetime.to_time) #converts stringlike dates without time
assert Date.to_mongo(datetime).eql?(datetime.to_time) #converts date with hour,min,sec
assert Date.to_mongo(date).eql?(date.to_datetime.to_time) #converts date without time
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment