I can get Rails to display mm/dd/yyyy using the following initializer:
date_format.rb
Date::DATE_FORMATS[:default]="%m/%d/%Y"
or l18n using this answer
But this does not change the way dates are submitted. When submitted:
10/02/2014
Will be parsed as
@entry.photo_date
Mon, 10 Feb 2014
I'm looking for a way to submit a date in mm/dd/yyyy format.
I'd like to be able to do this centrally, so I do not have to repeat code throughout the application
In modern ruby (ie. with prepend
) you can insert your own type casting in front of Rails's. You'll want to do this for whatever other date/time formats you're using. Here's the code for Date
, just stick this in an 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 fall back to using the builtin method if that didn't work.
Try this:
irb(main):001:0> today = Date.today
=> Tue, 06 Jan 2015
irb(main):003:0> today.strftime("%m/%d/%Y")
=> "01/06/2015"
So in your case, @entry.photo_date.strftime("%m/%d/%Y")
should work.
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