hilton meyer

Dates in 11ty used in templates

Yesterday was looking for a way to add the updated date to my static site, generated by 11ty, at the bottom of each article. I wanted to show the creation date and the last updated. I started will the following in my layout but the date being returned was then out put as "Last updated Thu Sep 19 2019 03:00:00 GMT+0300 (Israel Daylight Time)":

article.njk

---
layout: layouts/base.njk
templateClass: tmpl-article
---
<p class="title">{{ title }}</p>

{{ content | safe }}

Last updated {{ updated }}

So I now needed a way to format the date instead of getting back such an unwieldy string and having something a bit more human readable. To the docs I went and found that there was something on using dates. I saw they were using a Javascript method for correcting the dates .toUTCString(). this got me wondering what other things I could use and if it was simply the Date object. So I added .toString() and it worked. Well it worked in so much as I got back a full string with the date as above which is what .toString() does according to the documentation on MDN. I noticed there was .toDateString(). BINGO!!!

article.njk

---
layout: layouts/base.njk
templateClass: tmpl-article
---
<p class="title">{{ title }}</p>

{{ content | safe }}

<footer>Create on {{ page.date.toDateString() }} - Last updated {{ updated.toDateString() }}</footer>

You may have noticed that I added the page to the date for creation date as this is working and how the 11ty documentation describes to use Page Variable Content