How to make the default date format in the US when saving a model in Rails 3

The date in the USA was accepted / analyzed correctly, but no more in Rails 3.% Y-% m-% d is accepted, but not% m /% d /% Y.

g = Grant.new g.budget_begin_date = '12/31/2010' #g.budget_begin_date returns nil g.budget_begin_date = '2010-12-31' #g.budget_begin_date returns Fri, 31 Dec 2010 00:00:00 UTC +00:00 
+7
ruby-on-rails-3
source share
5 answers

Starting with Ruby 1.9, Date.parse stopped processing the ambiguous format mm / dd / yyyy (American format) or dd / mm / yyyy (the rest of the civilized world).

american_date gem linked here makes an assumption older than Ruby, and therefore can parse the American date as expected.

+4
source share

The example of your code does not quite show Date.parse, unable to interpret US style dates, but you're right, it is not. Instead of this:

 Date.parse("12/31/2010") 

Use this:

 Date.strptime("12/31/2010", "%m/%d/%Y") 
+4
source share

If you are not averse to using a gem, you can check out Chronic Stone: https://github.com/mojombo/chronic

You may have a chronic analysis of the start date before saving the model.

+1
source share

The Date class calls the self.parse method to parse the provided string before the date.

 1.9.2p320 :051 > x = Date.parse('2011-31-12') ArgumentError: invalid date from .../rubies/ruby-1.9.2-p320/lib/ruby/1.9.1/date.rb:1022:in `new_by_frags' from .../rubies/ruby-1.9.2-p320/lib/ruby/1.9.1/date.rb:1066:in `parse' 

which turns the self call into the _parse method, which is located in the file "... / ruby-1.9.2-p320 / lib / ruby โ€‹โ€‹/1.9.1/date/format.rb".

it calls the strftime function ("def strftime (fmt = '% F')"), where the default format for generating the date is "% F", which according to the documentation of the temporary class "% F is the date ISO 8601 format (% Y-% m-% d) ".

0
source share

In a modern ruby โ€‹โ€‹(i.e. with prepend ) you can insert your own type of casting before Rails. You will want to do this for any other date / time formats that you use. Here's the code for Date , just paste this in config/initializers/typecasts.rb or somewhere:

 module Typecasting module Date def cast_value v ::Date.strptime v, "%m/%d/%Y" rescue super end end ::ActiveRecord::Type::Date.prepend Date end 

Rails will try the American format and return to using the built-in method if this does not work.

0
source share

All Articles