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’]
[/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
[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
[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.
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)
Thanks for the tip Greg. I really appreciate it.
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ā
)