/ src / lib / utils / time-utils.ts
time-utils.ts
 1  import i18next from 'i18next';
 2  
 3  export const getFormattedDate = (commentTimestamp: number) => {
 4    if (commentTimestamp === undefined || isNaN(commentTimestamp)) {
 5      return '';
 6    }
 7    const locale = i18next.language || 'en';
 8    const string = new Intl.DateTimeFormat(locale, {
 9      hour12: false,
10      year: '2-digit',
11      month: '2-digit',
12      day: '2-digit',
13      weekday: 'short',
14      hour: '2-digit',
15      minute: '2-digit',
16      second: '2-digit',
17    }).format(new Date(commentTimestamp * 1000));
18    if (locale.startsWith('ar')) {
19      return string;
20    }
21    const items = string.split(/,* /);
22    if (items.length === 3) {
23      const itemIsNumber = [items[0][0].match(/[0-9]/), items[1][0].match(/[0-9]/)];
24      if (itemIsNumber[0] && itemIsNumber[1]) {
25        return `${items[0]}(${items[2]})${items[1]}`;
26      }
27      if (itemIsNumber[0] && !itemIsNumber[1]) {
28        return `${items[0]}(${items[1]})${items[2]}`;
29      }
30      if (!itemIsNumber[0] && itemIsNumber[1]) {
31        return `${items[1]}(${items[0]})${items[2]}`;
32      }
33    }
34    return string;
35  };
36  
37  export const getFormattedTimeAgo = (unixTimestamp: number): string => {
38    const currentTime = Date.now() / 1000;
39    const timeDifference = currentTime - unixTimestamp;
40    const t = i18next.t;
41  
42    if (timeDifference < 120) {
43      return t('time_1_minute_ago');
44    }
45    if (timeDifference < 3600) {
46      return t('time_x_minutes_ago', { count: Math.floor(timeDifference / 60) });
47    }
48    if (timeDifference < 7200) {
49      return t('time_1_hour_ago');
50    }
51    if (timeDifference < 86400) {
52      return t('time_x_hours_ago', { count: Math.floor(timeDifference / 3600) });
53    }
54    if (timeDifference < 172800) {
55      return t('time_1_day_ago');
56    }
57    if (timeDifference < 2592000) {
58      return t('time_x_days_ago', { count: Math.floor(timeDifference / 86400) });
59    }
60    if (timeDifference < 5184000) {
61      return t('time_1_month_ago');
62    }
63    if (timeDifference < 31104000) {
64      return t('time_x_months_ago', { count: Math.floor(timeDifference / 2592000) });
65    }
66    if (timeDifference < 62208000) {
67      return t('time_1_year_ago');
68    }
69    return t('time_x_years_ago', { count: Math.floor(timeDifference / 31104000) });
70  };