简体   繁体   中英

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

在我看来,我想以“mm / dd / yyyy”格式显示当前日期。

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

You could simply do (substitute in Time for DateTime if using straight Ruby -- ie 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.

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 .

如果您不需要全年,可以尝试Time.now.strftime('%D')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM