-
Notifications
You must be signed in to change notification settings - Fork 0
/
getRelativeDate.ts
48 lines (40 loc) · 1.66 KB
/
getRelativeDate.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { getDay, getDiffInDays, getDiffInHours, getDiffInMinutes, getDiffInMonths, getDiffInYears, getEndOfMonth } from '.';
import { ChronosDate, ensureDate } from './helpers/ensureDate';
/**
* Get relative date
* @param value
* @return - Relative date value
*/
export default (value: ChronosDate): string => {
const date = ensureDate(value);
const currentDate = new Date();
const minutes = getDiffInMinutes(currentDate, date);
const hours = getDiffInHours(currentDate, date);
const days = getDiffInDays(currentDate, date);
const months = getDiffInMonths(currentDate, date);
const years = getDiffInYears(currentDate, date);
let result = '';
if (!minutes) {
result = 'меньше минуты';
} else if (minutes < 60) {
result = `${minutes === 1 ? '' : `${minutes} `}${getPlural(minutes, 'минуту', 'минуты', 'минут')}`;
} else if (hours < 24) {
result = `${hours === 1 ? '' : `${hours} `}${getPlural(hours, 'час', 'часа', 'часов')}`;
} else if (days < getDay(getEndOfMonth(date))) {
result = `${days === 1 ? '' : `${days} `}${getPlural(days, 'день', 'дня', 'дней')}`;
} else if (months < 12) {
result = `${months === 1 ? '' : `${months} `}${getPlural(months, 'месяц', 'месяца', 'месяцев')}`;
} else {
result = `${years === 1 ? '' : `${years} `}${getPlural(years, 'год', 'года', 'лет')}`;
}
return result;
};
function getPlural(n: number, one: string, few: string, many: string): string {
if (n % 10 === 1 && n % 100 !== 11) {
return one;
}
if (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20)) {
return few;
}
return many;
}