const dateLocaleByLang = { sl: 'sl-SI', en: 'en-GB' } const dateOnlyOptions = { day: '2-digit', month: '2-digit', year: 'numeric' } const timeOnlyOptions = { hour: '2-digit', minute: '2-digit' } const dateTimeOptions = { ...dateOnlyOptions, ...timeOnlyOptions } function getDateLocale() { const lang = document.documentElement.lang || 'sl' return dateLocaleByLang[lang] || dateLocaleByLang.sl } function toDateOrNull(value) { const date = value instanceof Date ? value : new Date(value) return isNaN(date.getTime()) ? null : date } function formatDate(value) { const date = toDateOrNull(value) return date ? date.toLocaleDateString(getDateLocale(), dateOnlyOptions) : '' } function formatTime(value) { const date = toDateOrNull(value) return date ? date.toLocaleTimeString(getDateLocale(), timeOnlyOptions) : '' } function formatDateTime(value) { const date = toDateOrNull(value) return date ? date.toLocaleString(getDateLocale(), dateTimeOptions) : '' } // Scans `root` (defaults to the whole document) for elements carrying a // data-timestamp attribute and fills them in using the browser's own // timezone. Call this again after injecting server-rendered HTML fragments // (e.g. AJAX-paginated results), since it only runs automatically once on // page load. function applyTimestamps(root) { const scope = root || document scope.querySelectorAll('[data-timestamp]').forEach(el => { const date = toDateOrNull(el.getAttribute('data-timestamp')) if (!date) return const datePart = el.querySelector('[data-timestamp-part="date"]') const timePart = el.querySelector('[data-timestamp-part="time"]') if (datePart || timePart) { if (datePart) datePart.textContent = formatDate(date) if (timePart) timePart.textContent = formatTime(date) } else if (el.getAttribute('data-timestamp-format') === 'date') { el.textContent = formatDate(date) } else { el.textContent = formatDateTime(date) } }) } window.DateUtils = { formatDate, formatTime, formatDateTime, applyTimestamps } window.addEventListener('load', () => applyTimestamps())