Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format DateTime in Text Box in Rails

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
like image 417
jerhinesmith Avatar asked Sep 14 '09 15:09

jerhinesmith


3 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'))
like image 77
Dave Rapin Avatar answered Oct 23 '22 11:10

Dave Rapin


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') %>
like image 36
Alessandra Pereyra Avatar answered Oct 23 '22 11:10

Alessandra Pereyra


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.

like image 4
Eimantas Avatar answered Oct 23 '22 13:10

Eimantas