Last active
September 11, 2023 05:10
-
-
Save adactio/ccca5710152e77fb26b4a4df0ea8fc1e to your computer and use it in GitHub Desktop.
Periodically update the text of `datetime` elements with the relative time elapsed.
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
(function (win, doc) { | |
'use strict'; | |
if (!doc.querySelectorAll || !win.Intl || !win.Intl.RelativeTimeFormat) { | |
// doesn't cut the mustard. | |
return; | |
} | |
var rtf = new Intl.RelativeTimeFormat('en', { | |
localeMatcher: 'best fit', | |
numeric: 'always', | |
style: 'long' | |
}); | |
var units = { | |
'year' : 1000 * 24 * 60 * 60 * 365, | |
'month' : 1000 * 24 * 60 * 60 * (365/12), | |
'week' : 1000 * 24 * 60 * 60 * 7, | |
'day' : 1000 * 24 * 60 * 60, | |
'hour' : 1000 * 60 * 60, | |
'minute' : 1000 * 60, | |
'second' : 1000 | |
}; | |
var unit, then, now, diff, amount, text; | |
var updateDatetimes = function () { | |
now = Date.now(); | |
doc.querySelectorAll('time[datetime]').forEach(function(timeElement) { | |
text = 'just now'; | |
then = timeElement.getAttribute('datetime'); | |
diff = new Date(then) - new Date(now); | |
for (unit in units) { | |
amount = units[unit]; | |
if (Math.abs(diff) > amount) { | |
text = rtf.format(Math.round(diff / amount), unit); | |
break; | |
} | |
} | |
timeElement.innerText = text; | |
}); | |
}; | |
// Run the update every 30 seconds | |
setInterval(updateDatetimes, units.second * 30); | |
}(this, this.document)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment