dr Hannibal Lecter
dr Hannibal Lecter

Reputation: 6721

How do I format date and/or time input in Ruby on Rails?

This question is asking virtually the same as this:

Except the top answer is not working for me. I'm new to both Ruby and RoR, so I'm not sure what the heck am I doing anyway. Here is what I have so far.

I've added the default date and time format in my en.yml:

en:
  date:
    formats:
      default: '%d.%m.%Y'
  time:
    formats:
      default: '%H:%M'

I've also added a new initializer with the following code:

Date::DATE_FORMATS[:default] = '%d.%m.%Y'
Time::DATE_FORMATS[:default] = '%H:%M'

When I go to rails console and do Time.now.to_s or Date.today.to_s I get correct results. These also display correctly when fetched from the database and shown on a model index page for example.

However, when I try to create a form with some date and time fields (not datetime!), I get the good old YYYY-MM-DD for dates, and the whole YYYY-MM-DD HH:mm:ss.nnnnnn for time.

What would be the best practise to format these input values correctly? I'd like to avoid changing anything in the view (like it's done here), and solve this properly - on the application level - if it's possible at all.

Upvotes: 2

Views: 3718

Answers (1)

dr Hannibal Lecter
dr Hannibal Lecter

Reputation: 6721

This is what I ended up doing:

First I've defined a custom field in the model:

  attr_accessible :entry_date_formatted

  def entry_date_formatted
    self.entry_date.strftime '%d.%m.%Y' unless self.entry_date.nil?
  end

  def entry_date_formatted=(value)
    return if value.nil? or value.blank?
    self.entry_date = DateTime.strptime(value, '%d.%m.%Y').to_date
  end

Then I've changed my form from entry_date to entry_date_formatted:

<%= form.text_field :entry_date_formatted, :placeholder => 'Date' %>

Last but not least, I've added the relevant fields to my locale file:

en:
  activerecord:
    attributes:
      time_entry:
        entry_date_formatted: Entry date
        start_time_formatted: Start time
        end_time_formatted: End time

This is probably not the best way, but it serves me well for now.

Upvotes: 3

Related Questions