Continuing to make progress, little by little, I added dates to articles. In Contentful, this meant creating a new
date field on the article’s content model, which is easy enough, but surprisingly, you can’t set the default date to the current date. This adds an extra step to the authoring flow, but it’s not the end of the world.
On the frontend, I added a
<time> element under the article template’s title. This element takes a
datetime attribute for a machine-readable format of the date, which lets you use any human-readable format for the element’s contents. For date formatting, I’m using date-fns, a lightweight date utility library that I also use in my app, Cushion.
The latest date-fns release only works with integers or
Date objects, so first I needed parse Contentful’s dates. Previously, you could use the
date-fns/parse method on any string, and it would handle it.
Now, you need to pass the format of the date that you’re parsing.
For Contentful’s dates, this looks like
parse(article.fields.date, "yyyy-MM-dd'T'HH:mmXXX", new Date). The last argument here is a “backup date” required by date-fns to provide context to the original date, in case you’re parsing a date format with only 2-digit years. In my case, since the Contentful date format is standard, I can blindly pass the method a new
Date object simply to prevent a missing argument error. Now that I have a parsed date, I can format the date into a human-readable format. For now, I’m using
MMMM do, yyyy, which outputs to “November 3rd, 2019” for today’s date.
Along with the dates on the site itself, I also added the dates to my RSS feed by included a
date property when calling
addItem in the @nuxt/feed configuration. This method takes a
Date object, so I needed to parse Contentful’s date again, but no need to format this time.
When I added all the new date fields to my Contentful entries, I noticed that the order changed. Because I wasn’t specifying an order when retrieving the entries, they used the
updatedAt date, so when I set the
date field on all the entries, that changed the order. Now that I have my own
date field, the fix was as easy as setting the
order property to
'-fields.date,-sys.createdAt', which uses my new field, and falls back to the created timestamp.