time ago, a relative time calculator
posted on April 8, 2015, 10:42 pm in
A vanilla JavaScript relative time calculator.
the code
/*
* UI-Timeago (April 9 2015)
* Copyright 2015, http://codeeverywhere.ca
* Licensed under the MIT license.
*/
(function() {
var useAbbr = true;
//from jQuery
var isNumeric = function(obj) {
return (obj - parseFloat(obj) + 1) >= 0;
};
var secondsToString = function(sec) {
var years = Math.floor(sec / (604800 * 52) );
sec -= (years * 604800 * 52);
var weeks = Math.floor(sec / 604800);
sec -= (weeks * 604800);
var days = Math.floor(sec / 86400);
sec -= (days * 86400);
var hours = Math.floor(sec / 3600);
var minutes = Math.floor((sec - (hours * 3600)) / 60);
var buffer = '';
if (!useAbbr) {
if (years > 1) buffer += years + ' years ';
if (years == 1) buffer += '1 year ';
if (weeks > 1) buffer += weeks + ' weeks ';
if (weeks == 1) buffer += '1 week ';
if (days > 1) buffer += days + ' days ';
if (days == 1) buffer += '1 day ';
if (hours > 1) buffer += hours + ' hours ';
if (hours == 1) buffer += '1 hour ';
if (minutes > 1) buffer += minutes + ' minutes ';
if (minutes == 1) buffer += '1 minute';
} else {
if (years >= 1) buffer += years + 'y ';
if (weeks >= 1) buffer += weeks + 'w ';
if (days >= 1) buffer += days + 'd ';
if (hours >= 1) buffer += hours + 'h ';
if (minutes >= 1) buffer += minutes + 'm ';
}
return buffer;
};
setInterval(function() {
var times = document.getElementsByClassName("timeago");
//loop thru .ui-timeago
for (var x = 0; x < times.length; x++) {
var innerHTML, d, attr, now = new Date();
if (times[x].hasAttribute("data-timestamp"))
innerHTML = times[x].getAttribute("data-timestamp");
else
innerHTML = times[x].innerHTML;
//is UNIX or MySQL Timestamp
if (isNumeric(innerHTML)) {
d = new Date(parseInt(innerHTML) * 1000);
d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
} else {
var t = innerHTML.split(/[- :]/);
d = new Date(parseInt(t[0]), parseInt(t[1]) - 1, parseInt(t[2]), parseInt(t[3]), parseInt(t[4]), parseInt(t[5]));
d.setTime(d.getTime() + d.getTimezoneOffset());
}
//standardize timezone
now.setTime(now.getTime() + now.getTimezoneOffset() * 60 * 1000);
//find diff
var diff = (Math.floor(now.getTime() / 1000) - Math.floor(d.getTime() / 1000));
attr = document.createAttribute('data-timestamp');
attr.value = innerHTML;
times[x].setAttributeNode(attr);
if (Math.abs(diff) < 60)
times[x].innerHTML = "just now";
else if (diff < 0)
times[x].innerHTML = "in " + secondsToString(diff * -1); //-1 since neg val
else
times[x].innerHTML = secondsToString(diff) + " ago";
}
}, 2500);
})();
example usage
Add the JavaScript to your page and use .ui-timeago css class to activate. The inner section can be a UNIX timestamp or YYYY-MM-DD HH:MM:SS in UTC.
<div class="timeago">1428544787</div>
<div class="timeago">2015-04-09 01:59:47</div>
<div class="timeago">2016-11-09 01:59:47</div>
Watch it reload in real-time:
1428544787
2015-04-09 01:59:47
2016-11-09 01:59:47
Online Demo
Online demo: jsfiddle.net/se8ur2p9/