Adding a Date Format Filter in Nuxt

September 28, 2020

Since NuxtJS is just an opinionated VueJS with built in state management and routing, writing a filter for your template is just the same for Nuxt as it is for Vue, except for one catch.

For now, let's start with a date formatter inside a component.

Inside your component script tag, give the extends method your options object with a property of filters. Filter will be an object literal. The property names will be the name of the filter within the component.

I don't really have any fancy formatting in mind, so let's just call this filter "formatDate".

From a little bit of googling, I found the built in Intl.DateTimeFormat.

This looks like it's exactly what we need. It seems to handle language specific formatting as well as time zones. I don't really need those yet, and I only write in English so I'm used to seeing the mm/dd/yyyy. For now, I think that's enough for me.

<script lang="ts">
import Vue from "vue";
export default Vue.extend({
  filters: {
    formatDate: (date: Date) =>
      Intl.DateTimeFormat("us-EN").format(date),
  },
});
</script>

One snag is that I'm using Nuxt Content and I want to show the createdAt string that the module provides based on when the markdown file was created. createdAt returns a date in the form of a string, so I'll have to update the filter to handle that directly.

<script lang="ts">
import Vue from "vue";
export default Vue.extend({
  filters: {
    formatDate: (dateStr: string) =>
      Intl.DateTimeFormat("us-EN").format(new Date(dateStr)),
  },
});
</script>

If we test that in the template, it seems to work just fine.

<template>
  <div>
    Date: {{ post.createdAt | formatDate }}
  <div>
</template>

Now, this filter seems pretty useful. I'd think we would need this in a lot of pages and components so we should make this filter available to all the templates.

In plain Vue, you can just register the filter with Vue like so:

Vue.filter("formatDate", (dateStr: string) =>
  Intl.DateTimeFormat("us-EN").format(new Date(dateStr))
);

It's actually just the same in Nuxt, but we will be putting the filter in a plugin that's registered in the nuxt.config.ts file.

In the /plugins directory, create a file called format-date.ts. We "plugins" we put here are run before the root VueJS app gets instantiated.

/plugins/format-date.ts
import Vue from "vue";

Vue.filter("formatDate", (dateStr: string) =>
  Intl.DateTimeFormat("us-EN").format(new Date(dateStr))
);

If we check our prior rendered page, the filter should still work after the page hot reloads.

Subscribe

I'd like to send you a weekly recap of all the articles I write as well as my take on the latest news on web development with Vue, React, Elixir/Phoenix, and others. Just fill out your email and name below!