Skip to content

Instantly share code, notes, and snippets.

@luckyshot
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luckyshot/163ba130f73c85c9e103 to your computer and use it in GitHub Desktop.
Save luckyshot/163ba130f73c85c9e103 to your computer and use it in GitHub Desktop.
Nice relative time (ago) (multilanguage)
/*
Returns a MySQL date as: '2 days ago', 'right now', '14 hours ago'...
If date is older than 7 days then it displays it as 'September 1'
// Example
console.log( nice_time('2014-09-01 13:12:01') );
// Spanish config
var options = {
periods: ['segundo', 'minuto', 'hora', 'dia'],
lengths: [60, 60, 24, 7 ],
ago: 'hace',
now: 'justo ahora',
months: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Setiembre', 'Octubre', 'Noviembre', 'Diciembre'],
format: function(diff, j) {
if (diff != 1) {
this.periods[j]+= "s";
}
return this.ago+' '+diff+' '+this.periods[j]
}
};
// Spanish Example
console.log( nice_time('2014-09-01 13:12:01', options) );
*/
function nice_time(mysqldatetime, options) {
var config = options || {
periods: ['second', 'minute', 'hour', 'day'],
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
lengths: [60, 60, 24, 7],
ago: 'ago',
now: 'right now',
format: function(diff) {
return this.ago+' '+diff+' '+this.periods[j]+((diff != 1)?'s':'');
}
},
now = new Date().getTime(),
timestamp = new Date(mysqldatetime.replace(' ', 'T')).getTime(),
diff = (now - timestamp) / 1000,
j = 0,
lengthslength = config.lengths.length;
if (diff < 2) {
return config.now;
}else if (diff > 604800) {
timestamp = new Date(timestamp);
return config.months[timestamp.getMonth()]+' '+timestamp.getDate();
}
for( ; diff >= config.lengths[j] && j < lengthslength-1; j++) {
diff /= config.lengths[j];
}
return config.format(Math.round(diff), j);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment