Custom Date Formats for Your Rails Application

5 Comments
Tags: , , , ,
Posted 13 May 2009 in Ruby on Rails

If you use a consistent date format often in your Rails applciation, it is worth it to add the format to your application environment. You can do this by adding  it to the bottom of the config/environment.rb file.

Time::DATE_FORMATS[:my_custom_format] = "%A %B %d, %Y"

Now you can use it in your views like this

@post.created_at.to_s(:my_custom_format)

Which will output something like Monday May 5, 2009

Related posts:

  1. Rails Helper to Remove Leading Zero in 12 Hour Time Format
  2. Date and Time Helpers in Rails
  3. Generate MySQL Datetime Type Using PHP Date() Function
  4. Install and Serve a Rails Application from PHP Subdirectory Using Apache, Phussion Passenger and Ruby Enterprise Edition
  5. How to Install Ferret, the Full Text Search Engine with Your Rails Application

5 Comments

  1. Or you can store the format a file config/initializers/date_formats.rb with the ff code:

    ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
    :my_custom_format => “%A %B %d, %Y”
    )

  2. bseanvt

    Thanks! I was using a datetime type field from the db (created_at/updated_at) so I needed to add it to the Time module instead.

    ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
    :simple => “%A %B %d, %Y”
    )

  3. Cheers for this.

    I have the following in /config/initializers/time_formats.rb:

    ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
    :sentence => lambda { |date| date.strftime(“%B #{date.day.ordinalize}, %Y, at %l.%M”) + date.strftime.downcase(“%p”) }
    )

    I have the following in a view:

    I get this error when I load the view in a browser:

    wrong number of arguments (0 for 1)

    I get no error (but no formatting) if I instead use this in the view:

    Any idea what’s going on?

  4. admin

    Yeah, You have the wrong method order converting AM/PM to lowercase.

    You have in your code

    date.strftime.downcase(”%p”)
    

    But you need

    date.strftime("%p").downcase
    

    You’re getting an argument error because of this.

  5. Love your work. Got it in one.



Add Your Comment