trainUs/src/utils/dateFormatter.js
David 166cf87e95 F8: Date formatting uses Intl per app language
formatDate special-cased only French, so Danish users saw US
mm/dd/yyyy; formatDateTime mixed a manual French format with
toLocaleString() (OS-locale dependent) for everyone else. Both now use
Intl.DateTimeFormat with a fixed app-language -> BCP-47 map (en-US,
fr-FR, da-DK — same mapping as useSpeech), 2-digit day/month so output
stays deterministic per language: en 03/15/2026, fr 15/03/2026,
da 15.03.2026. Adds a Danish format test.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 15:41:51 +02:00

62 lines
1.8 KiB
JavaScript

import i18next from 'i18next'
// App language → BCP-47 tag (same mapping as useSpeech.js). Fixed tags keep
// the output deterministic per app language regardless of the OS locale, so
// tests can assert it (en: 03/15/2026, fr: 15/03/2026, da: 15.03.2026).
const LANG_MAP = { en: 'en-US', fr: 'fr-FR', da: 'da-DK' }
function toLangTag(lang) {
return LANG_MAP[lang || i18next.language] || LANG_MAP.en
}
export function formatDate(date, lang) {
if (!date) return ''
const d = date instanceof Date ? date : new Date(date)
if (isNaN(d.getTime())) return ''
return new Intl.DateTimeFormat(toLangTag(lang), {
day: '2-digit',
month: '2-digit',
year: 'numeric',
}).format(d)
}
export function formatItemDuration(ms) {
if (!ms || ms <= 0) return null
const totalSecs = Math.round(ms / 1000)
if (totalSecs <= 0) return null
const mins = Math.floor(totalSecs / 60)
const secs = totalSecs % 60
if (mins === 0) return `${secs}s`
if (secs === 0) return `${mins}min`
return `${mins}min${secs}s`
}
export function formatDuration(start, end) {
if (!start || !end) return null
const s = start instanceof Date ? start : new Date(start)
const e = end instanceof Date ? end : new Date(end)
if (isNaN(s.getTime()) || isNaN(e.getTime())) return null
const mins = Math.round((e - s) / 60000)
if (mins <= 0) return null
if (mins < 60) return `${mins} min`
const h = Math.floor(mins / 60)
const m = mins % 60
return m === 0 ? `${h}h` : `${h}h ${m}min`
}
export function formatDateTime(date, lang) {
if (!date) return ''
const d = date instanceof Date ? date : new Date(date)
if (isNaN(d.getTime())) return ''
return new Intl.DateTimeFormat(toLangTag(lang), {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
}).format(d)
}