При работе с функцией render библиотека использует
атрибут datetime. Однако для расширенного управления
поведением элементов — локалью, форматом, автообновлением — применяются
data-атрибуты.
Единственный атрибут, который render читает по
умолчанию:
<time datetime="2025-05-26T10:00:00Z"></time>
Значение должно быть совместимо с new Date().
timeago.js не читает data-атрибуты самостоятельно. Для
их использования нужен собственный код инициализации.
HTML:
<time
class="ago"
datetime="2025-05-26T10:00:00Z"
data-locale="ru"
data-max-days="7"
>
</time>
Jav * aScript:
import { render } from 'timeago.js';
document.querySelectorAll('.ago').forEach(el => {
const locale = el.dataset.locale || 'en_US';
render(el, locale);
});
Управление локалью на уровне элемента:
<time class="ago" datetime="2025-05-26T08:00:00Z" data-locale="ru"></time>
<time class="ago" datetime="2025-05-26T08:00:00Z" data-locale="de"></time>
<time class="ago" datetime="2025-05-26T08:00:00Z" data-locale="ar"></time>
import { render } from 'timeago.js';
document.querySelectorAll('.ago').forEach(el => {
render(el, el.dataset.locale || 'en_US');
});
Маркировка элементов для глобальной инициализации:
<time data-timeago datetime="2025-05-26T08:00:00Z"></time>
<time data-timeago datetime="2025-05-25T14:00:00Z"></time>
import { render } from 'timeago.js';
const nodes = document.querySelectorAll('[data-timeago]');
render(nodes, 'ru');
Иногда datetime занят или не подходит семантически:
<span data-date="2025-05-26T08:00:00Z" class="time-label"></span>
import { format } from 'timeago.js';
document.querySelectorAll('.time-label').forEach(el => {
const date = el.dataset.date;
if (date) el.textContent = format(date, 'ru');
});
<time
class="auto-time"
datetime="2025-05-26T08:00:00Z"
data-interval="10000"
>
</time>
import { format } from 'timeago.js';
document.querySelectorAll('.auto-time').forEach(el => {
const date = el.getAttribute('datetime');
const interval = parseInt(el.dataset.interval) || 60000;
function update() {
el.textContent = format(date, 'ru');
}
update();
setInterval(update, interval);
});
<time
class="smart-time"
datetime="2024-01-01T00:00:00Z"
data-max-days="30"
>
</time>
import { format } from 'timeago.js';
document.querySelectorAll('.smart-time').forEach(el => {
const date = el.getAttribute('datetime');
const maxDays = parseFloat(el.dataset.maxDays) || Infinity;
const ageDays = (Date.now() - new Date(date).getTime()) / 86400000;
if (ageDays > maxDays) {
el.textContent = new Intl.DateTimeFormat('ru', {
dateStyle: 'medium',
}).format(new Date(date));
} else {
el.textContent = format(date, 'ru');
}
});
<time
class="with-tooltip"
datetime="2025-05-26T08:00:00Z"
data-title-format="full"
>
</time>
import { format } from 'timeago.js';
document.querySelectorAll('.with-tooltip').forEach(el => {
const date = el.getAttribute('datetime');
el.textContent = format(date, 'ru');
el.title = new Intl.DateTimeFormat('ru', {
dateStyle: 'full',
timeStyle: 'medium',
}).format(new Date(date));
});
import { render, format } from 'timeago.js';
function initTimeElements() {
const elements = document.querySelectorAll('[data-timeago]');
elements.forEach(el => {
const locale = el.dataset.locale || 'ru';
const maxDays = el.dataset.maxDays ? parseFloat(el.dataset.maxDays) : null;
const date = el.getAttribute('datetime') || el.dataset.date;
if (!date) return;
const ageDays = (Date.now() - new Date(date).getTime()) / 86400000;
if (maxDays !== null && Math.abs(ageDays) > maxDays) {
el.textContent = new Intl.DateTimeFormat(locale, {
dateStyle: 'medium',
}).format(new Date(date));
} else {
render(el, locale);
}
});
}
document.addEventListener('DOMContentLoaded', initTimeElements);
| Атрибут | Тип | Назначение |
|---|---|---|
data-timeago |
boolean | Маркер для автоинициализации |
data-locale |
string | Локаль элемента |
data-date |
string | Альтернатива datetime |
data-max-days |
number | Максимум дней для относительного формата |
data-interval |
number | Кастомный интервал обновления (мс) |