SHA256
55 lines
2.6 KiB
JavaScript
55 lines
2.6 KiB
JavaScript
// Единое форматирование пользовательских дат, времени и чисел.
|
|
// UI-язык общий для всех профилей; часы — в часовом поясе устройства.
|
|
import { getLanguage } from './index.js';
|
|
|
|
const LANGUAGE_DEFAULTS = { ru: 'ru-RU', en: 'en-US' };
|
|
|
|
export function getIntlLocale() {
|
|
const language = getLanguage();
|
|
const defaults = LANGUAGE_DEFAULTS[language] || language;
|
|
try {
|
|
const list = globalThis.navigator?.languages;
|
|
const candidates = Array.isArray(list) && list.length ? list : [globalThis.navigator?.language];
|
|
for (const candidate of candidates) {
|
|
const locale = String(candidate || '').trim().replace(/_/gu, '-');
|
|
if (locale.toLowerCase().split('-')[0] !== language) continue;
|
|
// Не принимаем некорректную локаль из browser API.
|
|
try {
|
|
const canonical = Intl.getCanonicalLocales(locale)[0];
|
|
return canonical.includes('-') ? canonical : defaults;
|
|
} catch { /* try next */ }
|
|
}
|
|
} catch { /* no navigator e.g. in tests */ }
|
|
return defaults;
|
|
}
|
|
|
|
// Для MVP даты и время отображаем в европейском порядке (день–месяц–год,
|
|
// 24-часовые часы), в том числе при запасной английской локали en-US.
|
|
// Числовые разделители берём из выбранной локали.
|
|
export function getDateLocale() {
|
|
const locale = getIntlLocale();
|
|
return locale.toLowerCase().startsWith('en-us') ? 'en-GB' : locale;
|
|
}
|
|
|
|
export function formatDate(value, options = { day: 'numeric', month: 'long', year: 'numeric' }) {
|
|
return new Intl.DateTimeFormat(getDateLocale(), options).format(value instanceof Date ? value : new Date(value));
|
|
}
|
|
|
|
export function formatTime(value, options = { hour: '2-digit', minute: '2-digit' }) {
|
|
return new Intl.DateTimeFormat(getDateLocale(), { hourCycle: 'h23', ...options }).format(value instanceof Date ? value : new Date(value));
|
|
}
|
|
|
|
export function formatDateTime(value, options = {
|
|
day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit',
|
|
}) {
|
|
return new Intl.DateTimeFormat(getDateLocale(), { hourCycle: 'h23', ...options }).format(value instanceof Date ? value : new Date(value));
|
|
}
|
|
|
|
export function formatNumber(value, options = {}) {
|
|
return new Intl.NumberFormat(getIntlLocale(), options).format(value);
|
|
}
|
|
|
|
export function formatRelative(value, unit, options = {}) {
|
|
return new Intl.RelativeTimeFormat(getIntlLocale(), { numeric: 'auto', ...options }).format(value, unit);
|
|
}
|