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

前端 未结 4 1704
猫巷女王i
猫巷女王i 2020-12-08 12:48

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

4条回答
  •  独厮守ぢ
    2020-12-08 13:26

    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.

提交回复
热议问题