If I pass a String
into Datetime
column while creating new AR object, it will be automatically parse:
1.9.2p290 :011 > Movie.new(:release_date=>"21-Nov-1990")
=> #<Movie id: nil, release_date: "1990-11-21 00:00:00", created_at: nil, updated_at: nil>
How does Rails
, or ActiveRecord
, do this magic? Which method does it use?
As other comments and the documentation suggests, String#to_datetime "Converts a string to a DateTime value.":
Rails adds a
to_date
method toString
. Its source is simple:Date._parse
is native to Ruby (the same method is called byDate.parse
) and it's where the real work is done.It first uses a regular expression to remove extraneous symbols from the string, then passes it to other methods like
_parse_eu
,_parse_iso
,_parse_dot
and so on. Each of these uses its own regular expressions and other methods to see if it's a date that it understands and extract the meaningful information from it. Once one of them "works" (i.e. returns true), the rest are skipped. Finally, back in_parse
, the extracted information is used to build a date and time, doing a little more work to figure out things like checking for the day of the week and whether a year value of "12" should mean 1912 or 2012.The docs call this a heuristic method, which could be taken to mean it throws a bunch of possibilities at the wall to see what sticks. It's pretty poorly-documented but works remarkably well.
There's also
to_datetime
if you need the time.You probably want to use
Date.strptime(str)
.