Skip to content

Instantly share code, notes, and snippets.

@jarthod
Last active February 14, 2016 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jarthod/83013ba128c1e77bbfed to your computer and use it in GitHub Desktop.
Save jarthod/83013ba128c1e77bbfed to your computer and use it in GitHub Desktop.
Rails helper to render time using client's browser locale
# Use this in place of `time_tag`
# Ex: <%= local_time_tag user.created_at %>
def local_time_tag time, opts = {}
opts[:data] = (opts[:data] || {}).merge format: 'local'
opts[:title] ||= time
time_tag(time, opts) + content_tag(:script, raw(<<-JAVASCRIPT))
var nodes = document.querySelectorAll('time[data-format=local]');
if (nodes.length > 0) {
var elem = nodes[nodes.length - 1];
var time = new Date(elem.getAttribute('datetime'));
if (time.toLocaleString) { elem.innerHTML = time.toLocaleString() }
}
JAVASCRIPT
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment