Skip to content

Instantly share code, notes, and snippets.

@goofballLogic
Created October 28, 2021 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goofballLogic/a6b374eff82e1a1de3dccdf622912577 to your computer and use it in GitHub Desktop.
Save goofballLogic/a6b374eff82e1a1de3dccdf622912577 to your computer and use it in GitHub Desktop.
const fullFormat = new Intl.DateTimeFormat("en", { dateStyle: "full" });
const ordinalSuffixes = {
"one": "st",
"two": "nd",
"few": "rd",
"other": "th"
};
const ordinalPluralRules = new Intl.PluralRules("en", { type: "ordinal" });
function withOrdinalSuffix(x) {
if(typeof x != "number") throw new TypeError(`Expected Number but received ${typeof x}`);
if(x < 1) throw new RangeError(`Expected a number > 0 but received ${x}`);
const ordinal = ordinalPluralRules.select(x);
if (!ordinal in ordinalSuffixes) throw new Error(`Unexpected ordinal ${ordinal}`);
const suffix = ordinalSuffixes[ordinal];
return `${x}${suffix}`;
}
const now = new Date();
const parts = fullFormat.formatToParts(now);
const weekDayName = parts.find(p => p.type === "weekday").value;
const dayName = parts.find(p => p.type === "day").value;
const dayWithSuffix = withOrdinalSuffix(Number(dayName));
`${weekDayName} ${dayWithSuffix}` // Thursday 28th
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment