Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting dates in US format: mm/dd/yyyy

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

like image 302
jamesdlivesinatree Avatar asked Jan 06 '15 18:01

jamesdlivesinatree


Video Answer


2 Answers

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.

like image 123
smathy Avatar answered Oct 22 '22 09:10

smathy


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.

like image 28
neo Avatar answered Oct 22 '22 10:10

neo