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

Published on September 6, 2020 52 sec read

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. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *