Skip to content

Instantly share code, notes, and snippets.

@korun
Forked from codeincontext/gist:1285806
Last active August 29, 2015 14:05
Show Gist options
  • Save korun/187f26f045cee3cbe85c to your computer and use it in GitHub Desktop.
Save korun/187f26f045cee3cbe85c to your computer and use it in GitHub Desktop.
Javascript function to show how long ago a timestamp was as a pretty string (support Russian language and genitive)
// time in seconds
// genitive - использовать ли родительный падеж (true / false)
(function (){
var units = [
{ name: "second", limit: 60, in_seconds: 1 },
{ name: "minute", limit: 3600, in_seconds: 60 },
{ name: "hour", limit: 86400, in_seconds: 3600 },
{ name: "day", limit: 604800, in_seconds: 86400 },
{ name: "week", limit: 2629743, in_seconds: 604800 },
{ name: "month", limit: 31556926, in_seconds: 2629743 },
{ name: "year", limit: null, in_seconds: 31556926 }
];
var ru_locale = {
second: {name: 'секунд', one: ['а', 'у'], few: 'ы', many: ''},
minute: {name: 'минут', one: ['а', 'у'], few: 'ы', many: ''},
hour: {name: 'час', one: '', few: 'а', many: 'ов'},
day: {name: '', one: 'день', few: 'дня', many: 'дней'},
week: {name: 'недел', one: ['я', 'ю'], few: 'и', many: 'ь'},
month: {name: 'месяц', one: '', few: 'а', many: 'ев'},
year: {name: '', one: 'год', few: 'года', many: 'лет'}
};
var locale = function (name, number, genitive) {
var e;
if (number > 10 && number < 20)
e = 'many';
else {
number = number % 10;
e = number == 1 ? 'one' : (number < 5 && number > 1 ? 'few' : 'many');
}
var ends = ru_locale[name][e];
if (typeof ends !== 'string')
ends = ends[genitive ? 1 : 0];
return ru_locale[name].name + ends;
};
window.timeAgo = function (time, genitive) {
genitive = genitive || false;
var diff = (new Date() - new Date(time * 1000)) / 1000;
if (diff < 5) return "только что";
var i = 0, unit;
while (unit = units[i++]) {
if (diff < unit.limit || !unit.limit) {
diff = Math.floor(diff / unit.in_seconds);
return diff + " " + locale(unit.name, diff, genitive);
}
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment