Created
October 28, 2021 17:34
-
-
Save goofballLogic/a6b374eff82e1a1de3dccdf622912577 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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