datenunjuckseleventy

11ty - How do I display post / page year?


I'm using Eleventy and using Posts. I have set the date in the meta data using the format

date: 2021-09-10.

I can display the full date using

{{ page.date | readableDate }}

But I want to display just the year (YYYY) within the post content. I'm using Nunjucks.

How do i do this?

I've tried

{{ page.date.getFullYear }}

This gives the following error:

function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return obj[val].apply(obj, args); }

Any help would be really appreciated - thanks!


Solution

  • Add a filter to your .eleventy.js file

    eleventyConfig.addFilter("justYear", (dateString) => {
        dateObj = new Date(dateString);
        return DateTime.fromJSDate(dateObj, { zone: 'utc' }).toFormat('yyyy');
    });
    

    Then in your .njk file

    {{ page.date | justYear }}