How to display current date in mm / dd / yyyy format in Rails

In my opinion, I want to display the current date in the format "mm / dd / yyyy".

+54
date ruby ruby-on-rails
Sep 09 '10 at 14:53
source share
4 answers
<%= Time.now.strftime("%m/%d/%Y") %> 
+106
Sep 09 '10 at 14:58
source share

You could just do it (replace Time with DateTime if using direct Ruby - i.e. Rails):

 DateTime.now.strftime('%m/%d/%Y') 

If you use this format a lot, you may need to create a date_time_formats initializer in your RAILS_ROOT/config/initializers folder (assuming Rails 2), something like this:

 # File: date_time_formats.rb ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!( :human => "%m/%d/%Y" ) 

Which allows you to use a more friendly version of DateTime.now.to_s(:human) in your code.

+19
Sep 09 '10 at 14:57
source share

I think you can use .strftime :

 t = Time.now() t.strftime("The date is %m/%d/%y") 

This should give "The date is 09/09/10" . See here for a large list of format codes for .strftime .

+6
Sep 09 2018-10-09T00:
source share

If you don’t need a full year, you can try Time.now.strftime('%D')

0
Mar 04 '15 at 10:47
source share



All Articles