Mark Thomas Miller's logo

How to fix Eleventy's dates being off by one day

July 12, 2020

Eleventy's dates are usually off by one day. For instance, if you set the date to 2020-01-01, it will actually render something like December 31st 2019. This is because Eleventy's dates, which are in UTC, are being converted into a local timezone.

In this post, we'll cover how to create a human-friendly date for your templates. Eleventy recommends a fix in its documentation, but it leaves you with a long date string like Mon, 01 Jan 2020 00:00:00 GMT, which isn't very human-readable, so we'll make a better solution.

To make it easier to work with dates, we'll install Moment.js. Run:

npm install moment --save

Then, inside your .eleventy.js file, add the following Liquid filter. If you don't have this file yet, see the side tutorial below.

// Import Moment
const moment = require("moment");

// ...

// Inside the function you export...
eleventy.addLiquidFilter("toUTCString", (date) => {
  const utc = date.toUTCString();
  return moment.utc(utc).format("MMMM Do YYYY");
});

Working with .eleventy.js

You can add custom filters to Eleventy by creating an .eleventy.js file in your site's root directory. (The name of this file starts with a period.) Inside this file, you can export a JavaScript function.

If you are creating your .eleventy.js file because of this tutorial, this is the entirety of what you'll need:

const moment = require("moment");

module.exports = function (eleventy) {
  eleventy.addLiquidFilter("toUTCString", (date) => {
    const utc = date.toUTCString();
    return moment.utc(utc).format("MMMM Do YYYY");
  });
}

Now, inside your Liquid template, you can use one of these to return the correctly formatted date:

# this
{{ date | toUTCString }}

# or this
{{ page.date | toUTCString }}

If you are here from my Eleventy guide, you can click here to return.