I’m having trouble working with the datetime format. Current situation:
I’m having a database with a few fields with datetime in it. The format is like 2011-11-16 15:07:00 UTC. I woud like to change this format throughout my application. I don’t care if it is saved this way in the database, but I want it a little bit more customer-friendly in the corresponding views (I’m from Germany, so that would be 16.11.2011 15:07).
I tried to use I18n, which worked at least for a few parts. I created a locale (and added default_locale to application.rb). Is there a way that rails uses this locale without altering the corresponding views? I couldn’t find it, so I (succesfully) tried the following:
For my index-view I’ve worked with a little function in the
application_helper.rb:
module ApplicationHelper
def nice_date_form(the_date)
if !the_date.nil?
I18n.l the_date, :format => :short
end
end
end
Problems arose when I tried to use that approach with the edit/new views (_form.html.erb), it just didn’t work at all. After a while I came across a RailsCast about the topic virtual attributes, which at least temporary solved my problem. I can use a getter and setter methode in the model, but for different tables and fields that would be a whole lot of repetition.
_form.html.erb:
(...)
<div class="field">
<%= f.label :abfahrt %><br />
<%= f.text_field :nice_date_edit %>
</div>
(...)
Long story short: I searched a long while now and don’t know where to continue. I guess that this can’t be the best approach to solve this issue? Is there a way to simplify that and set kind of a rails-wide format for datetime?
A few hints would be greatly appreciated! Thanks in advance.
Christian
You can use strftime() for formatting datetime in the view label(customer-friendly in the corresponding views).
Your helper method could be
For details take a look at Rails Datetime Format