How can I use US-style dates in Rails using Ruby 1.9? -
I I am in, and we usually format the date as "month / day / year". I am trying to make sure that my Rail App, using Ruby 1.9, receives this format everywhere, and works the way it works under Ruby 1.8.
I know that many people have this problem, so I want to make a definite guide here.
Specifically:
- '04 / 01/2011 'is April 1, 2011, not January 4, 2011
- '4/1/2011' is also April 1, 2011 - leading zero should not be necessary.
How can I do this?
Even so far away from me.
Controlling the behavior of the date # to_s
I have this code in the
application.rb : "12/25/2011 'dated: DATE_FORMATS [ : Default] = Format our dates like '% m /% d /% Y'
P> ensures that if I do the following:
d = date. New (2011,4,1) d.to_s
... I get "04/01/2011" "2011-04-01" No.
Controlling String # to_date behavior
The
string # to_date of ActiveSupport currently looks like this Is ():
def to_date ret Color Neil if self.black ?: Date.new (* :: Date._parse (self, false) .values_at (: year,: som, : Mday)) End
(If you do not follow that, the second line creates a new date in that order, year, month and day. The way this year, Receives the values of months and days, it is used by the
Date._parse , which defines the string and somehow those values, then returns a hash.
.values_at pulls the sequence out of that hish in
Date.new in order.)
Because I know that I usually " 04/01/2011 "or" 4/1/2011 ", I can turn it off and turn it off:
class string # An indicator is the string of ActiveSupport # To_date alias_method: old_to_date ,: to_date # Define it if def._date return blue is self.blank? Get started # Start by handling values in this order, / month, day, year = self-edit ('/'). Map (and: to_i) :: Date. New (year, month, day) Rescue # If it fails - "April 4, 2011" - Start coming back to basic practice old_to_date Rescue NoMethodError = & gt; E # Ruby Date- Stupid, Unusual Error If E-mails == "Undefined Method`" For Nil: NilClass "Invalid DatError.new (" # {self} is not a valid date "increment from the intestines of the parsing code ) And E & End & End & End & amp; Class Achievement Enter & lt; standard error; End; This solution passes my test, but is it crazy? Am I missing a configuration option somewhere, or is there a few more easy solutions?
Am I not covering any other date-parsing cases?
gem: ruby-american-date
since this gem I have The question was asked. Now I am using it and am happy.
Comments
Post a Comment