Skip to content

Instantly share code, notes, and snippets.

@kopiro
Created August 23, 2012 17:32
Show Gist options
  • Save kopiro/3439145 to your computer and use it in GitHub Desktop.
Save kopiro/3439145 to your computer and use it in GitHub Desktop.
Kopiro TimeAgo
Date.prototype.timeAgoString = function(granularity)
{
var t = this.timeAgo(granularity);
var r = [];
for (var i=0; i<t.length; i++)
r.push( t[i].time+' '+t[i].key );
return r.join(' e ');
}
Date.prototype.timeAgo = function(granularity)
{
var difference = new Date().getTime() - this.getTime();
difference = Math.abs(difference) / 1000;
var retVal = [];
if (!granularity) granularity = 2;
var periods =
{
'decad':315360000,
'ann':31536000,
'mes':2628000,
'settiman':604800,
'giorn':86400,
'or':3600,
'minut':60,
'second':1
};
for (var key in periods)
{
var value = periods[key];
if ( difference >= value )
{
var time = Math.round(difference/value);
difference %= value;
if (time>1)
{
if ( key=='or' || key=='settiman' ) key += 'e';
else key += 'i';
}
else
{
if ( key=='second' || key=='minut' || key=='giorn' ) key += 'o';
else if ( key=='or' || key=='settiman' )key += 'a';
else key += 'e';
}
retVal.push({ key:key, time:time });
granularity--;
}
if (!granularity) break;
}
return retVal;
}
$(function(){
setInterval(function(){
$('.timeago').each(function(k,el)
{
el = $(el);
var dt = el.attr('datetime');
if (!dt) return;
dt = new Date(dt);
el.html( dt.timeAgoString() );
});
}, 1000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment