The Spaghetti Refactory Established 2015

Format your Time the easy way with Rails locales

If you haven't ever used locales in Rails before, you're in for a treat. This is a super powerful feature bundled with Rails in the rails-i18n gem. The Ruby on Rails guide for it packs a lot of info to cover all types of scenarios, but I'm going to talk here about a couple very simple tweaks you can make to easily format your Date, Time, and Datetime objects consistently across your entire site.
First, this post is going to assume your app is written in English, and the instructions that follow are written specifically for that scenario, but locales work for any language, so you just need to place your code in the proper YAML file.
Let's say you want all of your Datetime or Time objects in your app formatted in the Month Date, Year - HH:MM Meridian format (i.e. June 25, 2009 - 10:24 PM). The old fashioned way is to have to use .strftime('%B %d, %Y - %H:%M %p'). Don't get me wrong, I love me some strftime, but I don't want to be having to type or copypasta that stuff every time. Here's what we're going to do instead:

# config/locales/en.yml
en:
time:
formats:
full: "%B %d, %Y - %H:%M %p"
Then, in your views wherever you want your Time object (for example, object.created_at)to be formatted this way, instead of this:

object.created_at.strftime('%B %d, %Y - %H:%M %p')
Do this:

l object.created_at, format: :full
The 'l' prefacing your object is a locale method, and the Time object gets passed in as an argument, with the formatting option that you want to use. Now, if you have a couple different formats you use throughout your app, say :full, :date_only, and :time_with_zone, this makes it so much easier to use.

# config/locales/en.yml
en:
time:
formats:
full: "%B %d, %Y - %H:%M %p"
date_only: "%B %d, %Y"
time_with_zone: "%-m/%-d/%y %-I:%M %p %Z"
Instead of trying to remember the alphabet soup of strftime, it is way cooler to just call your locale method with the human-readable format you want.

Tags