Start · Sprachen · JavaScript · Snippets · Datum lokalisiert formatieren (Intl)

Datum lokalisiert formatieren (Intl)

Datum & Zeit

Formatiert ein Datum mit Intl.DateTimeFormat passend zu Sprache und Zeitzone. Formatter werden zwischengespeichert, ungültige Datumswerte lösen einen Fehler aus.

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