SnippetsSnippets
date2Clear
Get formatted date with ordinals

Get date formatted with ordinals (st, nd, rd, th, etc) using JavaScript's Intl.

const getFormattedDate = (dateString: string, locale = 'en-IN') => {
  const ordinalMap: Partial<Record<Intl.LDMLPluralRule, string>> = {
    one: 'st',
    two: 'nd',
    few: 'rd',
    other: 'th',
  };
  const ordinalPluralRules = new Intl.PluralRules(locale, { type: 'ordinal' });

  const formatter = new Intl.DateTimeFormat(locale, {
    day: 'numeric',
    month: 'long',
    year: 'numeric',
  });
  const dateParts = formatter.formatToParts(new Date(dateString));

  // Modify day part by adding ordinal
  const dayPart = dateParts.find((p) => p.type === 'day')!;
  const ordinal = ordinalMap[ordinalPluralRules.select(Number(dayPart.value))];
  dayPart.value = dayPart.value + ordinal;

  return dateParts.map((p) => p.value).join('');
};

Example usage and outputs:

getFormattedDate('03-22-2023');
// "22nd March 2023"

getFormattedDate('08-17-2023', 'en-US');
// "August 17th, 2023"

getFormattedDate('12-31-2023', 'en-GB');
// "31st December 2023"

Limitations

This logic only works for English locales and might not work for others like French, German, etc.

Get formatted date for a timezone

Convert a timestamp in millis to a particular timezone using JavaScript's Intl.

const getDateForTimeZone = (
  millis: number,
  tz: string,
  locale = 'en-IN'
): string => {
  const dateFormatter = new Intl.DateTimeFormat(locale, {
    timeZone: tz,
    day: 'numeric',
    month: 'short',
    year: 'numeric',
  });

  const timeFormatter = new Intl.DateTimeFormat(locale, {
    timeZone: tz,
    timeStyle: 'short',
  });

  const timezoneFormatter = new Intl.DateTimeFormat(locale, {
    timeZone: tz,
    timeZoneName: 'long',
  });

  return [
    `${dateFormatter.format(millis)}`,
    `${timeFormatter.format(millis).toUpperCase()}`,
    `${timezoneFormatter.formatToParts(millis).find((p) => p.type === 'timeZoneName')?.value || ''}`,
  ].join(' ');
};

Example usage and outputs:

getDateForTimeZone(1690113193308, 'Asia/Kolkata');
// 23 Jul 2023 5:23 PM India Standard Time

getDateForTimeZone(1690113193308, 'America/Chicago', 'en-US');
// Jul 23, 2023 6:53 AM Central Daylight Time

getDateForTimeZone(1690113193308, 'Europe/Paris', 'fr-FR');
// 23 juil. 2023 13:53 heure d’été d’Europe centrale