Date Formatting With Custom Rails Helper

Vamsi Krishna

58 sec read

Some people really hate working with Date Formatting because, it drives you crazy while doing so. The same thing happened to me as well, not until I shifted to Ruby on Rails. While I wanted to display custom date, I was searching in google to find some wayout. I didn’t find any direct solution, so I thought I would share my solution here. An excuse to write a blog. šŸ˜‰

So, i will cover..
1) How to format date in Ruby
2) How to use custom view helpers in Rails to show the custom datetime.
Let’s see how the page would look without formatting
dateformatting2
Isn’t it ugly? Let’s see how it looks after formatting
dateformatting1
What I just did is
[sourcecode language=’HTML’]

<%=h display_date(record.published_on) %>

[/sourcecode]
Is Rails doing this for us ? no, we are doing for ourselves with a custom helper display_date.
Ok, some expanation now
Rails came up with so many helpers for making developer’s job easy. Still they can’t provide everything we want So, you can writer your own helper methods to use in the view files
viewhelper
[sourcecode language=’Ruby’]
module RecordsHelper
def display_date(input_date)
return input_date.strftime(“%d %B %Y”)
end
end
[/sourcecode]
strftime method Formats date and time according to the input given to that method. Let’s see a different format
viewhelper
[sourcecode language=’ruby’]
module RecordsHelper
def display_date(input_date)
return input_date.strftime(“%d %B %Y at %I:%M%p”)
end
end
[/sourcecode]
To see more formats visit the link below
http://www.ruby-doc.org/core-1.9/classes/Time.src/M000257.html
finally, you can do the same things if you want to format phone number’s, post code and so on.

Related posts:

4 Replies to “Date Formatting With Custom Rails Helper”

  1. Another approach would be to create a file config/initializers/date_formats.rb with the ff code:
    ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
    :Ymd => “%Y-%m-%d”
    )
    This way you can do input_date.to_s(:Ymd)

  2. By the way, the above nice tip by Greg Moreno would work for Date object only. If you want to apply it for Time object then simply change it to
    ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
    :Ymd => ā€œ%Y-%m-%dā€
    )

Leave a Reply

Your email address will not be published. Required fields are marked *