Skip to content

Instantly share code, notes, and snippets.

@kucheruk
Created December 24, 2015 08:52
Show Gist options
  • Save kucheruk/fe452451e0004b210c2c to your computer and use it in GitHub Desktop.
Save kucheruk/fe452451e0004b210c2c to your computer and use it in GitHub Desktop.
js snippets
export function declination(number, titles) {
const cases = [2, 0, 1, 1, 1, 2];
return titles[(number % 100 > 4 && number % 100 < 20) ? 2 : cases[(number % 10 < 5) ? number % 10 : 5]];
}
const SECOND = 1000;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const WEEK = 7 * DAY;
const YEAR = DAY * 365;
const MONTH = YEAR / 12;
const formats = [
[0.7 * MINUTE, 'только что'],
[1.5 * MINUTE, 'минуту назад'],
[60 * MINUTE, ['минуту назад', 'минуты назад', 'минут назад'], MINUTE],
[1.5 * HOUR, 'час назад'],
[DAY, ['час назад', 'часа назад', 'часов назад'], HOUR],
[2 * DAY, 'вчера'],
[7 * DAY, ['день назад', 'дня назад', 'дней назад'], DAY],
[1.5 * WEEK, 'неделю назад'],
[MONTH, ['неделю назад', 'недели назад', 'недель назад'], WEEK],
[1.5 * MONTH, 'месяц назад'],
[YEAR, ['месяц назад', 'месяца назад', 'месяцев назад'], MONTH],
[1.5 * YEAR, 'год назад'],
[Number.MAX_VALUE, ['год назад', 'года назад', 'лет назад'], YEAR],
];
export function relativeDate(input) {
const referenceT = (new Date).getTime();
const inputT = input.getTime();
const delta = referenceT - inputT;
let format;
for (let i = 0; i < formats.length; i++) {
format = formats[i];
if (delta < format[0]) {
if (format[2] === undefined)
return format[1];
let num = Math.round(delta / format[2]);
return num + ' ' + declination(num, format[1]);
}
}
}
export function formatTimeRelative(datetime) {
return relativeDate(datetime);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment