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
Isn’t it ugly? Let’s see how it looks after formatting
What I just did is
[sourcecode language=’HTML’]

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

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
[sourcecode language=’Ruby’]
module RecordsHelper
def display_date(input_date)
return input_date.strftime(“%d %B %Y”)
strftime method Formats date and time according to the input given to that method. Let’s see a different format
[sourcecode language=’ruby’]
module RecordsHelper
def display_date(input_date)
return input_date.strftime(“%d %B %Y at %I:%M%p”)
To see more formats visit the link below
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:
    :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
    :Ymd => ā€œ%Y-%m-%dā€

Leave a Reply

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