Skip to content
Branch: master
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
53 lines (41 sloc) 3.03 KB
layout title categories published meta
Easier DateTime Localisation with Rails
– blog
description index
Rails ships with a bunch ISO date formats (and a few localised ones), here is how to use them

Ruby and Rails come with a bunch of time saving libraries, which can save you a lot of time coding for specific scenarios.

Pure Ruby

These are the methods which ship with Ruby's DateTime class, with their associated strftime format. Where possible you should use these when storing times, or outputing data in some machine readable way (Like an API).

Method strftime Format Output %a, %d %b %Y %H:%M:%S GMT Sun, 03 Mar 2019 13:45:03 GMT %Y-%m-%dT%H:%M:%S+%H:%M 2019-03-03T13:45:17+00:00 H%d.%m.%yT%H:%M:%S+%H:%M H31.03.03T13:45:26+00:00 %Y-%m-%dT%H:%M:%S+%H:%M 2019-03-03T13:45:37+00:00 %a, %-d %b %Y %H:%M:%S +%H%M Sun, 3 Mar 2019 13:45:48 +0000 %a, %-d %b %Y %H:%M:%S +%H%M Sun, 3 Mar 2019 13:45:58 +0000 %Y-%m-%dT%H:%M:%S+%H:%M 2019-03-03T13:49:32+00:00 %s 1551621698
{: class='table table-striped table-bordered'}


Non-developers are a bit rubbish at reading those standardised formats. Luckily, Rails has your back with a bit of I18n awesomeness! It ships with 3 localisation formats (default, short & long), that'll output dates nicely.

Code Output
I18n.l(, format: :default) Sun, 03 Mar 2019 14:17:01 +0000
I18n.l(, format: :short) 03 Mar 14:17
I18n.l(, format: :long) March 03, 2019 14:17
{: class='table table-striped table-bordered'}

By default, rails ships with the :en locale. However, pretty often you'll want to localise your dates and times to different international formats, for this the rails-i18n gem to save you a bunch of time.

Add that gem to your Gemfile, then you can either set the locale from the Accept-Language browser header, or just pass the format argument to your I18n.l method call.

Code Output
I18n.l(, format: :long, locale: :'en-US') March 03, 2019 02:37 PM
I18n.l(, format: :long, locale: :'en-GB') 03 March, 2019 14:38
I18n.l(, format: :long, locale: :'de') Sonntag, 03. März 2019, 14:38 Uhr
{: class='table table-striped table-bordered'}

This should handle most your date & time formatting needs when outputting to various users :D

You can’t perform that action at this time.