Is there an easy way to format the display of a DateTime
value in a Rails view?
For example, if I\'m doing something like:
<%= text_field
This can be handled DRYly at the model layer using the Rails-provided <attribute>_before_type_cast
method variant. Rails already uses this method for doing just this type of formatting, so we're just overwriting the default. For example:
class MyModel
def start_date_before_type_cast
return unless self[:start_date]
self[:start_date].strftime('%m/%d/%Y')
end
end
This way, anywhere you have a text field for the MyModel#start_date field you get formatting for "free".
In a helper
def l(value, options = {})
return nil unless value.present?
value = value.to_date if value.is_a? String
super(value, options)
end
Then in the view
<%= f.text_field :end_date, class: "datepicker" :value => l(@activity.end_date) %>
Here l
is a rails helper (I18n.l
) which can be locale specific and can take a format. Examples:
l(@activity.end_date, format: :short)
l(@activity.end_date, format: "%d-%m-%Y")
I can think of three ways:
1) Creating a new method on the model that would format your date however you need it to be
2) Creating a helper method that would do the same
3) Have you tried doing:
<%= text_field
:my_object,
:start_date,
:value => @my_object.try(:start_date).try(:strftime,'%m/%d/%Y') %>
If your form is tied to an object, (something like <% form_for(:object) do |f| %>
) you should use <%= f.text_field :start_date, :value => f.object.start_date.to_s(:date_format) %>
then you can register your :date_format
in config/environment.rb
Not sure why you want to do this, but i hope it's for presentation purposes only.
if you don't want to enter the date in a textfield, but in a less error prone select field, you could use the ActionView::Helpers::DateHelper, select_date(). see Accessing date() variables send from the date helper in rails here on SO on how to process the return values.
Some great suggestions here, however in those cases where you really do want your text field date formatted a specific way (say you're integrating with a javascript date picker), and you're dealing with nils, I think simply making a minor tweak to your existing method would do the trick:
:value => (@object.start_date.blank? ? '' : @object.start_date.strftime('%m/%d/%Y'))