DEV Community

Maxwell Adapoe
Maxwell Adapoe

Posted on

Create a simple time ago component in Vue using Moment.js

Ever needed a time ago component where you can parse a datetime string and get your date in the format like 10 days ago , a year ago etc.? Well you could create that easily in vue.js using moment.js.

Let's dive straight into it.

  1. Install moment.js using npm npm install moment --save or with yarn yarn add moment
  2. Create a new component. You can name it TimeAgo.vue
  3. In your component
//TimeAgo.js
<template>
<span>{{convertedDateTime}}</span>
</template>
<script>
import moment from 'moment'
export default {
  name: "TimeAgo",
  props:{
    dateTime:{
      required:true
    }
  },
  computed:{
    convertedDateTime(){
     return moment(this.dateTime).fromNow();
    }
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

to use it in your project

<template>
...
<time-ago :dateTime='new Date()'/>
...
</template>
<script>
import TimeAgo from "@/components/TimeAgo";

export default {
...
  components: {
    TimeAgo
  }
...
}
</script>
Enter fullscreen mode Exit fullscreen mode

and thats it. This should work in vue 2 and vue 3 without any issues. if you need to extend it you can see the moment.js docs

Top comments (0)