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 :my_object, :start_date %>
and only want to display the Date part of the :start_date
(i.e. I want to hide the time part), is there a way to format the :start_date
string inside of the view such that it will work for creating new my_object
items and updating new my_object
items?
Just a clarification:
Doing
<%= text_field
:my_object,
:start_date,
:value => @my_object.start_date.strftime('%m/%d/%Y') %>
works beautifully when the object already exists (i.e. on item updates), however, when creating a new item, since start_date will initially be nil, the view will throw an error
while evaluating nil.strftime
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'))
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With