Local <time> elements
npm install local-timeLocal Time makes it easy to display times and dates to users in their local time. Its Rails helpers render elements in UTC (making them cache friendly), and its JavaScript component immediately converts those elements from UTC to the browser's local time.
gem "local_time" to your Gemfile.bundle installbin/importmap pin local-time to add the local-time npm packageapp/javascript/application.js ``js`
import LocalTime from "local-time"
LocalTime.start()
document.addEventListener("turbo:morph", () => {
LocalTime.run()
})
to your Gemfile.
2. Run bundle install
3. Run yarn add local-time
4. Add this to app/javascript/packs/application.js
`js
import LocalTime from "local-time"
LocalTime.start()
`Example
`ruby
> comment.created_at
"Wed, 27 Nov 2013 18:43:22 EST -0500"
``erb
<%= local_time(comment.created_at) %>
`Renders:
`html
data-local="time"
datetime="2013-11-27T23:43:22Z">November 27, 2013 11:43pm
`And is converted client-side to:
`html
data-local="time"
datetime="2013-11-27T23:43:22Z"
title="November 27, 2013 6:43pm EDT"
data-localized="true">November 27, 2013 6:43pm
`(Line breaks added for readability)
Time and date helpers
`erb
<%= local_time(time) %>
`Format with a strftime string (default format shown here)
`erb
<%= local_time(time, '%B %e, %Y %l:%M%P') %>
`Alias for
local_time with a month-formatted default`erb
<%= local_date(time, '%B %e, %Y') %>
`To set attributes on the time tag, pass a hash as the second argument with a
:format key and your attributes.`erb
<%= local_time(time, format: '%B %e, %Y %l:%M%P', class: 'my-time') %>
`To use a strftime format already defined in your app, pass a symbol as the format.
`erb
<%= local_time(date, :long) %>
`When using the
local_time helper I18n.t("time.formats.#{format}"), I18n.t("date.formats.#{format}"), Time::DATE_FORMATS[format], and Date::DATE_FORMATS[format] will be scanned (in that order) for your format.When using the
local_date helper, I18n.t("date.formats.#{format}"), I18n.t("time.formats.#{format}"), Date::DATE_FORMATS[format], and Time::DATE_FORMATS[format] will be scanned (in that order) for your format.Note: The included strftime JavaScript implementation is not 100% complete. It supports the following directives:
%a %A %b %B %c %d %e %H %I %l %m %M %p %P %S %w %y %Y %ZTime ago helpers
`erb
<%= local_time_ago(time) %>
`Displays the relative amount of time passed. With age, the descriptions transition from {quantity of seconds, minutes, or hours} to {date + time} to {date}. The