Formatting dates nicely in 11ty with Luxon
Using Luxon to format dates in your nunjucks templates
Why do this?
Often dates aren't in nice human readable formats - this allows you to change the format to your needs.
In this case I'm using Luxon to format my dates.
Install Luxon
Luxon is a lightweight library for working with dates and times in JavaScript.
First install Luxon:
npm install luxon --save-dev
Then in your .eleventy.js
file require Luxon and include it as a const, which you can then refer to later.
Inside your module exports config function, register a filter:
const { DateTime } = require("luxon");
module.exports = function (config) {
config.addFilter("asPostDate", (dateObj) => {
return DateTime.fromJSDate(dateObj).toLocaleString(DateTime.DATE_MED);
// other config likely here
});
}
This uses Luxon to format a date object and converts it to a specific format.
The toLocaleString(DateTime.DATE_MED)
part is where you can choose the format of your date. Luxon has a bunch of useful presets.
Alternative: Using a custom date format
If none of the presets suit you, you can use custom formatting options which you would use like:
// this outputs Jul 2021
DateTime.fromJSDate(dateObj).toFormat("LLL yyyy");
N.B. I prefer registering simple filters directly in my .eleventy.js file
but for those with lots of filters, or filters that are more than a single line, registering them via an external file might be easiest. See the eleventy docs on filters.
Using the filter in your templates
I'm using Nunjucks here. When you output a variable in your template, use a pipe and then apply the filter name after that, and it will format your dates.
<span>{{ entry.data.date | asPostDate }}</span>
...ending up with something like the following being rendered:
<span>Jan 28, 2021</span>