Agoify
Based on http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time/ and http://timeago.yarp.com/
by drzaus
HTML
<a href="http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time/">Original StackOverflow Discussion</a>
<hr />
<p class="time" title="2013-09-25">This morning</p>
<p class="time" title="2013-09-27">Sept 27</p>
<p class="time" title="2013-09-26T09:12">+2 min</p>
<p class="time" title="1380203470798">DateTime.Now</p>
<hr />
<p class="time-data" data-date="2013-09-25">This morning</p>
<p class="time-data" data-date="2013-09-27">Sept 27</p>
<div id="output"></div>
CSS
pre { margin:0; padding:0; }
JavaScript
(function($) {
// #region ============== the plugin ===================
var agoify = function (time) {
// allow string or date or timestamp
time = time instanceof Date && time.getTime() ||
typeof time === "string" && Date.parse(time) ||
time;
// difference in total minutes (ms -> min)
var suf, delta = ( new Date().getTime() - time ) / 60000;
// log("comparing times", new Date().getTime(), time, delta);
// get suffix, "abs"
if(delta > 0) {
suf = " ago";
} else {
suf = " from now";
delta = -delta;
}
// lifted almost verbatim from jquery-timego plugin,
// modified from agoify thresholds on stackoverflow
// it's weird how javascript logic works... :)
return (delta < 0.75 && "less than a minute" ||
delta < 1.5 && "a minute" ||
delta < 45 && Math.round(delta) + " minutes" ||
delta < 90 && "an hour" ||
delta < 1440 /* 60 * 24 */ && Math.round(delta / 60) + " hours" ||
delta < 2880 && "a day" ||
delta < 43200 /* 60 * 24 * 30 */ && Math.round(delta / (60 * 24)) + " days" ||
delta < 86400 /* 60 * 24 * 60 */ && "a month" ||
delta < 525600 /* 60 * 24 * 365 */ && Math.round(delta / (60 * 24 * 30)) + " months" ||
delta < 1051200 /* 60 * 24 * 365 * 2 */ && "a year" ||
Math.round(delta / (60 * 24 * 365)) + " years"
) + suf;
}//-- fn agoify
// #endregion ============== the plugin ===================
// #region ============== make it jquery! ===================
$.fn.humanDate = function(attr) {
this.each(function(i,t) {
var $t = $(t), d = $t.attr(attr || 'title');
// log('humanDate', attr, d, Date.parse(d));
$t.attr(attr || 'title', $t.text()).text(agoify(d));
});
};
// #endregion ============== make it jquery! ===================
// #region ============== debug stuff ===================
var $output = document.getElementById('output');
var log =...