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?
Rails adds a to_date
method to String
. Its source is simple:
# File activesupport/lib/active_support/core_ext/string/conversions.rb, line 42
def to_date
return nil if self.blank?
::Date.new(*::Date._parse(self, false).values_at(:year, :mon, :mday))
end
Date._parse
is native to Ruby (the same method is called by Date.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With