Created
December 8, 2011 15:57
-
-
Save orlando/1447413 to your computer and use it in GitHub Desktop.
Date.to_mongo
This file contains 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
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 |
This file contains 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
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