JSFiddle - React, Tailwind, and code Playground
HTML
<input id="timestamp" value="2011-04-27T14:29:53Z">
<button id='go'>go</button> <pre id="output"></pre>
JavaScript
// inspired by http://momentjs.com/
unitMillisecondFactors = {
'Millisecond': 1000,
'Second': 60,
'Minute': 60,
'Hour': 24,
'Day': 356,
'Year': 10,
'Decade': 1
};
function compute_time(timestamp) {
var n = new Date() - new Date(timestamp);
var s = "";
for (var unit in unitMillisecondFactors) {
var factor = unitMillisecondFactors[unit];
s += "" + n + " " + unit + "s (factor for next unit: " + factor + ")\n";
if (n < factor) {
break;
}
n = n / factor;
}
n = Math.floor(n);
if (n == 1) {
return s + "more than " + n + " " + unit + " ago\n";
}Â
else {
return s + "more than " + n + " " + unit + "s ago\n";
}
}
document.getElementById('go').addEventListener('click', function () {
var input = document.getElementById('timestamp').value;
document.getElementById('output').innerHTML += compute_time(input);
});