Skip to content

Instantly share code, notes, and snippets.

@FlyInk13
Created November 29, 2017 21:07
Show Gist options
  • Save FlyInk13/ae1733827692531a768c9c260566cad4 to your computer and use it in GitHub Desktop.
Save FlyInk13/ae1733827692531a768c9c260566cad4 to your computer and use it in GitHub Desktop.
function declOfNum(number, titles) {
number = Math.abs(number);
return titles[(number % 100 > 4 && number % 100 < 20) ? 2 : [2, 0, 1, 1, 1, 2][(number % 10 < 5) ? number % 10 : 5]];
}
Date.prototype.DiffString = [
["секунду", "* секунды", "* секунд"],
["минуту", "* минуты", "* минут"],
["час", "* часа", "* часов"],
["день", "* дня", "* дней"],
["год", "* года", "* лет"],
["через *", "* назад", "прямо сейчас"]
];
Date.prototype.toDiffString = function (offset, lang) {
lang = lang || Date.prototype.DiffString;
offset = offset || [60, 3600, 86400, 31557600];
var now = Date.now();
var _this = this.getTime();
var diff = Math.floor(Math.abs(now - _this) / 1000);
var response = [];
for (var i = 0; i < offset.length; i++) {
response.push(diff % offset[i]);
if(i > 0) response[i] = Math.floor(response[i] / offset[i - 1]);
diff -= response[i];
}
response = response
.map((v, i) => declOfNum(v, lang[i]).replace("*", v))
.filter(v => v[0] !== "0")
.reverse();
if(!response.length) return lang[5][2];
return lang[5][(now > _this) * 1].replace("*", response.join(" "));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment