Formatting Dates: the Rails way
4th May 2018Working with dates in Rails can become a problem after a while, especially when in your project you have code like this:
t = Time.now
t.strftime("Printed on %m/%d/%Y")
At first glance, this might look good because this is a very simple date being formatted. But what happens when there are a lot of dates in many places and all of them with the same format? You end with a lot of strftime calls with the same arguments spread all over your project.
You might be thinking the solution would be to wrap the formatting in a helper method like:
...
def formatted_date(date)
date.strftime("Printed on %m/%d/%Y")
end
...
It does work, but there is a better way of doing it in Rails.
Managing custom date formats with Active Support
ActiveSupport is a Rails library that provides a lot of utility methods, one of those methods is the to_formatted_s
, here’s how it works:
t = Time.now
t.to_formatted_s(:iso8601) #=> "2018-05-03T16:17:33-05:00"
In order to add your own date formats you can create the following initializer file:
# config/initializers/date_formats.rb
Time::DATE_FORMATS[:flip_year] = '(╯°□°)╯︵%Y'
And now you can use your custom date formats everywhere like this:
t = Time.now
puts t.to_formatted_s(:flip_year) # => (╯°□°)╯︵2018
# or alias:
puts t.to_s(:flip_year) # => (╯°□°)╯︵2018
As you can see, this is a more organized way to keep all your date formats in a single place. The initializer file can work as a reference for other developers to figure out if there’s a format they can use and avoid code duplication.
View Comments