Formatting Dates in Eleventy using Filters

Learn how to transform dates into different formats in Eleventy using filters.

In Eleventy, I store the first published date of my posts and last modified date as frontmatter data using the format YYYY-MM-DD. For the first published date, I use the date keyword, that allows me to sort my collections easily.

At the end of the posts I render a paragraph similar to this:

<p>
  This post was first published on
  <time datetime="2024-06-07T00:00:00.000Z">7 June 2024</time>.
</p>

By using a filter you can transform the original frontmatter dates into the other date formats.

Setting up the function for date formatting

The function takes in two arguments: The date input like 2024-06-07 and the format key, that specifies how the date should be transformed.

Note that I’m using Eleventy v3, which lets you use ES Modules. In Eleventy v0, v1 and v2, you would need to use module.exports = function() instead of export default function().

export default function(dateInput, format) {

  // create a date object
  const date = new Date(dateInput);

  // handle the different cases
  switch (format) {
  
    // format the dates like `2024-06-07T00:00:00.000Z`
    // used in sitemap and <time> elements
    case 'iso':
      return date.toISOString();

    // render the date as english written text
    case 'plaintext':
      return date.toLocaleString('en-GB', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
      });

    default:
      throw Error('No valid format specified. Must be `iso` or `plaintext`');
  }
}

Adding the filter

Now we can add the function to the eleventy config file .eleventy.js as a filter.

// Import the date formatting function
import formatDate from './utils/formatDate.js';

export default function(config) {
  // Add the filter
  config.addFilter('formatDate', formatDate);
}

Using the function

Using the function is as easy as calling formatDate('2024-06-07', 'iso').

When using WebC for templating, it could look like this:

<p class="lastmod">
  This post was first published on
  <time
    :datetime="formatDate(date, 'iso')"
    @text="formatDate(date, 'plaintext')">
  </time><template webc:if="!lastmod" webc:nokeep>.</template>
  <template webc:if="lastmod" webc:nokeep>
    and last modified on
    <time
      :datetime="formatDate(lastmod, 'iso')"
      @text="formatDate(lastmod, 'plaintext')">
    </time>.
  </template>
</p>

This post was first published on and last modified on .