Format DateTime in Text Box in Rails
Solution 1
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'))
Solution 2
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') %>
Solution 3
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.
Solution 4
In my application_helper.rb I put
def nice_date_form(the_date)
return the_date.strftime('%d-%m-%Y')
end
In any edit.html.erb view file with a jQuery datepicker I then use:
<% if @activity.end_date? %>
<%= f.text_field :end_date, :value => nice_date_form(@activity.end_date) %>
<% else %>
<%= f.text_field :end_date %>
<% end %>
Solution 5
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".
Related videos on Youtube
jerhinesmith
I live and work near San Francisco, CA as a software engineer. In my spare time, I like to be as "sponge-like" as possible by reading, writing, and, yes, programming for fun.@jerhinesmith
Updated on July 09, 2022Comments
-
jerhinesmith almost 2 years
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 newmy_object
items and updating newmy_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
-
jerhinesmith over 14 yearsIt's mostly to prevent someone from thinking they need to or should input a time. For most users "2019-09-10 17:00:18" just isn't friendly. I'd much rather just be displaying "09/10/2009" since the time part is completely unnecessary for what I'm doing.
-
Eimantas over 14 yearsthen you should use select_date helper instead of plain input
-
Alessandra Pereyra over 14 yearsAgree, if it's for selecting a date, a Calendar or select_date helper are better approaches
-
jerhinesmith over 14 yearsI am using a calendar control, which works great when selecting a date -- you put the cursor in the text box, select the date from the calendar, and see your selection get written to the textbox. However, when going back to the page, the textbox is going to display the datetime from the DB, meaning that it will again have the time in there -- which is confusing. I'd personally rather not use select_date since the usability doesn't seem near as high as the calendar control I'm already using. Does that make sense?
-
Paul Schreiber over 13 yearsthis worked for me with one adjustment:
:value => (f.object.start_date.to_s(:date_format) unless f.object.start_date.nil?)
-
jerhinesmith over 13 yearsYou're missing a closing paren at the end, but otherwise this is what I did at first. I eventually went the route of just initializing the
start_date
to the current date in the object, so thatstart_date
would never benil
in the first place. -
Thomas Schmidt about 13 years@jerhinesmith You are absolute right. Did not test that properly. I changed the code above to test for nil. You could also do that the way Dave Rapin did it, in a nice one-liner.
-
jerhinesmith about 13 yearswhat if you changed
nice_date_form
to something likereturn (the_date ? the_date.strftime('%d-%m-%Y') : '')
. Then, you should be able to remove the conditional from the view. -
Thomas Schmidt about 13 years@jerhinesmith Sure, or going with Dave Rapin's idea, it would look like this: <%= f.text_field :start_date, :value => (@activity.start_date.blank? ? '' : nice_date_form(@activity.start_date)) %> One liners are great if you can see the logic in them. ;-)
-
Ole Henrik Skogstrøm almost 10 yearsEven cleaner: value: ( @object.start_date.strftime('%m/%d/%Y') unless @object.start_date.blank?)
-
Dave Rapin over 9 years@OleHenrikSkogstrøm nil is not the same as an empty string (which the datepickers I've used required). Definitely use an unless like that though if it works for you.