How to Install & Use Moment.js in Vue.js

In this guide, I’m going to show how to setup and use moment.js in Vue.js. Let’s get started:

Table of Contents

  1. Installation
  2. Examples

Installation

Run this command to install moment.js:

npm install moment --save   # npm
yarn add moment             # yarn

Examples

Now let’s see some examples.

Get current datetime:

<template>
  <div id="app">
    <p>{{currentDateTime()}}</p>
  </div>
</template>

<script>
import moment from 'moment'

export default {
  methods: {
    currentDateTime() {
      return moment().format('MMMM Do YYYY, h:mm:ss a')
    }
  }
};
</script>

Have a look at some usage of current datetime:

// an instance of momentjs
var current = moment()

// unix timestamp:
var current = moment().unix()

// as ISO
var current = moment().toISOString()

Check the date is today or not:

<template>
  <div id="app">
    <p>{{isToday("09-06-2020")}}</p>
  </div>
</template>

<script>
import moment from 'moment'

export default {
  methods: {
    isToday(date) {
      return moment(date).isSame(moment().clone().startOf('day'), 'd')
    }
  }
};
</script>

Change Language:

<template>
  <div id="app">
    <p>{{BDTime()}}</p>
  </div>
</template>

<script>
import moment from 'moment'

export default {
  methods: {
    BDTime() {
      moment.locale("bn") // bengali

      return moment().format('LTS')
    }
  }
};
</script>

To get more examples, please check moment.js’s official website.

That’s it. Thanks for reading. ?

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.