Rails date format in a text_field

后端 未结 14 2167
傲寒
傲寒 2020-12-13 06:05

I have a rails form that displays a date in a text_field:

<%= form.text_field :check_in_date  %>

The date is rendered as yyyy-m

相关标签:
14条回答
  • 2020-12-13 06:42

    I added these to my initializers/time_formats.rb and it works great:

    # Default format for displaying dates and times
    Date::DATE_FORMATS[:default] = "%m/%d/%Y"
    Time::DATE_FORMATS[:default] = "%m/%d/%Y"
    

    Using Ruby 1.9.3 and Rails 3.2.x

    0 讨论(0)
  • 2020-12-13 06:42

    config/initializers/date_format.rb

    ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS[:default] = '%m/%d/%Y'
    

    view

    <%= form.text_field :check_in_date, value: model.check_in_date.to_s %>
    
    0 讨论(0)
  • 2020-12-13 06:42

    So I did something like this in the model.

    def start_date
      super.strftime "%Y/%m/%d %H:%M"
    end
    

    Say you have a column called start_date in model, and want to display another format in the form, just overwrite its value in model.

    And nothing needs to be changed in the form.

    <%= f.text_field :start_date, class: 'form-control' %>
    
    0 讨论(0)
  • 2020-12-13 06:42

    A slight improvement of Tom Rossis answer is to use the I18n.localize method, so the default will always be in the current users locale:

    initializers/date_time_i18n_formatter.rb

    Date::DATE_FORMATS[:default] = ->(date) { I18n.localize date, format: :default }
    Time::DATE_FORMATS[:default] = ->(time) { I18n.localize time, format: :default }
    
    0 讨论(0)
  • 2020-12-13 06:48

    Go to your environment.rb file and add the following:

    ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
      :default => '%m-%d-%Y' ) 
    

    Check the official documentation if you feel like reading more :)

    0 讨论(0)
  • 2020-12-13 06:51

    This one use location, in your form:

    <%= f.text_field :date3, value: ( l @model.date3 if @model.date3? ) %>
    

    In locations en.yml (or es.yml)

    en:
      date:
        formats:
          default: "%d/%m/%Y"
    
    0 讨论(0)
提交回复
热议问题