Last active
February 14, 2016 15:21
-
-
Save jarthod/83013ba128c1e77bbfed to your computer and use it in GitHub Desktop.
Rails helper to render time using client's browser locale
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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