Format DateTime in Text Box in Rails

Viewed 25625

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
7 Answers

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'))
Related