DEV Community

Cover image for Day.js with RelativeTime in Nuxt.js
Sean Kerwin
Sean Kerwin

Posted on • Edited on

Day.js with RelativeTime in Nuxt.js

This is a relatively short guide, and it's just to show how easy it is to implement day.js inside a Nuxt app.

I've always just used Moment.js for date formatting, but since Moment.js has now been abandoned and they're encouraging people to use alternatives, I needed to find a way to convert timestamps that are provided by the API's I consume. They usually return timestamps in the following format:

2020-10-08T07:51:58Z
Enter fullscreen mode Exit fullscreen mode

Which to be honest, isn't really useful to anyone. That's where day.js comes in, it can convert the timestamp above into something like

Oct 8th 2020
Enter fullscreen mode Exit fullscreen mode

It's pretty simple to do.

First we need to pull in the @nuxtjs/dayjs package with the following command.

yarn add @nuxtjs/dayjs
or
npm install @nuxtjs/dayjs
Enter fullscreen mode Exit fullscreen mode

Once that is installed, open up your nuxt.config.js and add
'@nuxtjs/dayjs' to the modules section, and then outside of that, add the following dayjs object.

modules: [
    '@nuxtjs/dayjs',
    ...
],
dayjs: {
    locales: ['en'],
    defaultLocale: 'en',
    plugins: ['relativeTime', 'advancedFormat'],
},
Enter fullscreen mode Exit fullscreen mode

Set any locales you want, for me, being in the United Kingdom, I set my locale to en and then add any additional dayjs plugins you need. I'm using the RelativeTime and AdvancedFormat plugins.

Once everything is installed, you from within any component you can do the following

{{ $dayjs('2020-10-08T07:51:58Z').format('MMM Do YYYY') }}
Enter fullscreen mode Exit fullscreen mode

Which will output this

Oct 8th 2020
Enter fullscreen mode Exit fullscreen mode

You can also use the RelativeTime plugin to turn it into this:

{{ $dayjs('2020-10-08T07:51:58Z').fromNow() }}
Enter fullscreen mode Exit fullscreen mode

Which will return

a year ago

You can obviously, not use hard-coded dates and use props/variables such as

{{ $dayjs(post.published_at).fromNow() }}
Enter fullscreen mode Exit fullscreen mode

Day.js is a simple and ultra-lightweight replacement for Moment.js and is super easy to use.

Top comments (3)

Collapse
 
youyiqin profile image
yy1828

nice article!thanks!

Collapse
 
9mza profile image
9MZa

Thanks for your article. Help me so much. I find way to use this for Nuxtjs.

Collapse
 
iotapp profile image
Derek Flynn • Edited

Hey nice project, looks like there may be a viable alternative to moment.js :)