Custom Date Formats for Your Rails Application
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
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”
)
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?
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.
Love your work. Got it in one.
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”
)