Code
// Formatter-Erzeugung ist teuer -> pro Locale+Optionen cachen
const cache = new Map();
const formatDate = (value, { locale = 'de-DE', ...opts } = {}) => {
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime())) {
throw new RangeError(`Ungültiges Datum: ${value}`);
}
const key = `${locale}|${JSON.stringify(opts)}`;
let fmt = cache.get(key);
if (!fmt) {
fmt = new Intl.DateTimeFormat(locale, opts);
cache.set(key, fmt);
}
return fmt.format(date);
};
const d = '2024-03-15T14:30:00Z';
console.log(formatDate(d, { dateStyle: 'long', timeZone: 'Europe/Berlin' }));
console.log(formatDate(d, {
locale: 'en-US', dateStyle: 'full', timeStyle: 'short',
timeZone: 'America/New_York',
}));
15. März 2024
Friday, March 15, 2024 at 10:30 AM