Better looking dates in Eleventy
By default, the readableDate
in Eleventy will output dates in a rather robotic format: Dec 03 2022
. Let's do better and include the ordinal suffixes for each day:
For most numbers, we end with th, but not the 2nd or 3rd:
let ordinalSuffix = "th";
if (day === 1 || day === 21 || day === 31) {
ordinalSuffix = "st";
} else if (day === 2 || day === 22) {
ordinalSuffix = "nd";
} else if (day === 3 || day === 23) {
ordinalSuffix = "rd";
}
Here's the full code for .eleventy.js or your date converter:
function getOrdinal(number) {
const lastDigit = number % 10;
if ((number % 100 - lastDigit) === 10) return "th";
switch (lastDigit) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
eleventyConfig.addFilter("readableDate", dateObj => {
const dt = DateTime.fromJSDate(dateObj);
const day = dt.day;
return `${dt.toFormat('MMMM')} ${day}${getOrdinal(day)}, ${dt.toFormat('yyyy')}`;
});
That's it!