Files
AstralRinth/packages/ui/src/composables/format-date-time.ts
T
Jerozgen f62c60a681 Impove Intl formatting (#5372)
* Improve Intl formatting

* Additional fixes

* Fixed formatters were not updated on locale change

* Fixed formatNumber was not updated on locale change

* Additional formatting and fixes after merge

* Run prepr:frontend

* Remove `'` in icon map

* Run `pnpm install`

* fix: lint + import

* Additional fixes

---------

Co-authored-by: Calum H. <calum@modrinth.com>
Co-authored-by: Calum H. (IMB11) <contact@cal.engineer>
2026-03-09 21:29:32 +00:00

39 lines
1.0 KiB
TypeScript

import { LRUCache } from 'lru-cache'
import { injectI18n } from '../providers/i18n'
const formatterCache = new LRUCache<string, Intl.DateTimeFormat>({ max: 40 })
export function useFormatDateTime(options?: Intl.DateTimeFormatOptions) {
const { locale } = injectI18n()
function format(date?: Date | number | string): string {
if (typeof date === 'number' || typeof date === 'string') {
date = new Date(date)
}
const formatter = getFormatter(locale.value, options)
return formatter!.format(date)
}
return format
}
function getFormatter(locale: string, options?: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {
let cacheKey = locale
if (options) {
const entries = Object.entries(options)
.filter(([, value]) => value !== undefined)
.sort()
.map(([key, value]) => `${key}=${value}`)
cacheKey = [locale, ...entries].join(':')
}
let formatter = formatterCache.get(cacheKey)
if (!formatter) {
formatter = new Intl.DateTimeFormat(locale, options)
formatterCache.set(cacheKey, formatter)
}
return formatter
}