DEV Community

Daniel
Daniel

Posted on

Better Looking Dates in Eleventy: Jan 01 2023 --> Jan 1st 2023

By default, the default readableDate in Eleventy will output dates like: Dec 03 2022. Let's do better and set this up as the ordinal date.

For most numbers, we end with th:

    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";
    }
Enter fullscreen mode Exit fullscreen mode

Here's the full code for .eleventy.js or your date converter:

  function convertDate(dateString) {
    const date = new Date(dateString);
    const day = date.getDate();
    const month = date.getMonth();
    const year = date.getFullYear();
    const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    const monthName = monthNames[month];

    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";
    }

    return `${monthName} ${day}${ordinalSuffix}, ${year}`;
  }

  eleventyConfig.addFilter("readableDate", dateObj => {
    // Convert the date object to a date string using the convertDate() function 
    // And make sure you have nd, st, rd, or th after the day
    var dateString = convertDate(dateObj);
    return dateString;
  });
Enter fullscreen mode Exit fullscreen mode

This function takes advantage of the fact that most dates are ordinaled (if that's a word) with 'th'. We just have to add st to 1, 21, and 31... and then nd to 2 and 22, and we can't forget rd tacked onto 3 and 23.

Top comments (0)