akshay1188
akshay1188

Reputation: 1667

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

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

Upvotes: 71

Views: 90197

Answers (4)

jerhinesmith
jerhinesmith

Reputation: 15492

You could simply do (substitute in Time for DateTime if using straight Ruby -- i.e. no Rails):

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

If you're using that format a lot, you might want 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 will then let you use the more friendly version of DateTime.now.to_s(:human) in your code.

Upvotes: 27

Spyros
Spyros

Reputation: 247

If you don't need the full year you could try Time.now.strftime('%D')

Upvotes: 0

Budgie
Budgie

Reputation: 2279

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 great list of the format codes for .strftime.

Upvotes: 8

Jeff
Jeff

Reputation: 21892

<%= Time.now.strftime("%m/%d/%Y") %>

Upvotes: 137

Related Questions