Introduce
Gem local_time makes it easy for us to display the user’s date time with their local time. It supports the built-in rails helper to render into <time> tags in UT, then its js will convert that tag always from UTC to local browser time.
Setting
- Add
gem "local_time"
to Gemfile.=>
bundle install
- Add local-time.js in application.js
1 2 | <span class="token comment">//= require local-time</span> |
Usage and examples
This gem already has the following helper available:
Time and date helpers
- Default
1 2 | <%= local_time(time) %> |
For example
1 2 | <%= local_time(comment.created_at) %> |
- Format with strftime
Display datetime (default format)
1 2 | <%= local_time(time, '%B %e, %Y %l:%M%P') %> |
Display date (default format)
1 2 | <%= local_date(time, '%B %e, %Y') %> |
Use the strftime format defined in the App:
1 2 | <%= local_time(date, :long) %> |
In this format, it will scan in my App in the following order:
I18n.t("time.formats.#{format}")
, I18n.t("date.formats.#{format}")
, Time::DATE_FORMATS[format]
and Date::DATE_FORMATS[format]
Supported strftime format:
%a %A %b %B %c %d %e %H %I %l %m %M %p %P %S %w %y %Y %Z
Time ago helpers
Displays the amount of time elapsed compared to the current time
1 2 | <%= local_time_ago(time) %> |
For example with English:
- Recent: “a second ago”, “32 seconds ago”, “an hour ago”, “14 hours ago”
- Yesterday: “yesterday at 5:22 pm”
- This week: “Tuesday at 12:48 am”
- This year: “on Nov 17”
- Last year: “on Jan 31, 2012”
Configuration
Internationalization (I18n)
Its default will be English, but you can also create different languages. You can create the following new locale file with the format as its default file en translations :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | LocalTime.config.i18n["es"] = { date: { dayNames: [ … ], monthNames: [ … ], … }, time: { … }, datetime: { … } } LocalTime.config.locale = "es" |
You can find details in the official document here: