timeago.js занимает одну узкую нишу — форматирование относительного времени. Для полноценной работы с датами в сложных приложениях её часто используют совместно с другими библиотеками, каждая из которых решает свою задачу.
date-fns — функциональная библиотека для работы с
датами: парсинг, форматирование, арифметика. Связка с timeago.js:
import { format } from 'timeago.js';
import { parseISO, subDays, addHours } from 'date-fns';
// Парсинг через date-fns, форматирование через timeago.js
const date = parseISO('2025-05-26T10:00:00Z');
const formatted = format(date, 'ru');
// Арифметика через date-fns
const threeDaysAgo = subDays(new Date(), 3);
format(threeDaysAgo, 'ru');
// → "3 дня назад"
Распределение ответственности:
date-fns — создание и трансформация датtimeago.js — вывод относительного времениimport { format } from 'timeago.js';
import dayjs from 'dayjs';
const d = dayjs('2025-05-26T10:00:00Z');
format(d.toDate(), 'ru');
// → "4 часа назад"
Day.js удобен для форматирования абсолютных дат рядом с относительными:
const date = dayjs('2025-05-26T10:00:00Z');
const relative = format(date.toDate(), 'ru');
const absolute = date.format('DD.MM.YYYY HH:mm');
console.log(`${relative} (${absolute})`);
// → "4 часа назад (26.05.2025 10:00)"
import { format } from 'timeago.js';
import { DateTime } from 'luxon';
const dt = DateTime.fromISO('2025-05-26T10:00:00Z');
format(dt.toJSDate(), 'ru');
Luxon — мощный инструмент для работы с временными зонами и форматированием:
const dt = DateTime.fromISO('2025-05-26T10:00:00', { zone: 'Europe/Moscow' });
format(dt.toUTC().toJSDate(), 'ru');
import { format } from 'timeago.js';
import moment from 'moment';
const m = moment('2025-05-26T10:00:00Z');
format(m.toDate(), 'ru');
Moment.js устарел, но встречается в legacy-проектах. Конвертация
через .toDate() универсальна.
Temporal — будущий стандарт JavaScript для работы с датами:
import { format } from 'timeago.js';
import { Temporal } from '@js-temporal/polyfill';
const instant = Temporal.Instant.from('2025-05-26T10:00:00Z');
const jsDate = new Date(instant.epochMilliseconds);
format(jsDate, 'ru');
Интеграция с i18n-системами для синхронизации локали:
// React с react-intl
import { useIntl } from 'react-intl';
import { format } from 'timeago.js';
function TimeAgo({ date }) {
const intl = useIntl();
const locale = intl.locale; // 'ru', 'en', 'de'
return <time>{format(date, locale)}</time>;
}
import i18n from 'i18next';
import { format } from 'timeago.js';
const LOCALE_MAP = {
'ru': 'ru',
'en': 'en_US',
'de': 'de',
};
function relativeTime(date) {
const locale = LOCALE_MAP[i18n.language] || 'en_US';
return format(date, locale);
}
Обновление временных меток в реальном времени:
import { cancel, render } from 'timeago.js';
const socket = new WebSocket('wss://example.com/feed');
socket.onmess age = (event) => {
const data = JSON.parse(event.data);
const el = document.createElement('time');
el.setAttribute('datetime', data.createdAt);
el.setAttribute('class', 'feed-time');
document.getElementById('feed').prepend(el);
const all = document.querySelectorAll('.feed-time');
cancel(all);
render(all, 'ru');
};
import { useQuery } from '@tanstack/react-query';
import { format } from 'timeago.js';
function Post({ id }: { id: number }) {
const { data } = useQuery({
queryKey: ['post', id],
queryFn: () => fetch(`/api/posts/${id}`).then(r => r.json()),
});
if (!data) return null;
return (
<article>
<h2>{data.title}</h2>
<time>{format(data.createdAt, 'ru')}</time>
</article>
);
}
Стандартная схема работы с API:
import axios from 'axios';
import { format } from 'timeago.js';
async function getPosts() {
const { data } = await axios.get('/api/posts');
return data.map(post => ({
...post,
relativeTime: format(post.createdAt, 'ru'),
}));
}
import express from 'express';
import { format, register } from 'timeago.js';
import ru from 'timeago.js/esm/lang/ru';
register('ru', ru);
const app = express();
app.get('/posts', async (req, res) => {
const posts = await db.getPosts();
const enriched = posts.map(p => ({
...p,
timeAgo: format(p.createdAt, 'ru'),
}));
res.json(enriched);
});
| Задача | Библиотека |
|---|---|
| Относительное время | timeago.js |
| Абсолютное форматирование | date-fns / Luxon / Day.js |
| Арифметика с датами | date-fns / Luxon |
| Часовые пояса | date-fns-tz / Luxon |
| Парсинг нестандартных строк | date-fns/parse |
| Локализация интерфейса | i18next / react-intl |