Moment.js with Vuejs

Momentjsvue.js

Momentjs Problem Overview


I try to print out date time using like the following in vue-for

{{ moment().format('MMMM Do YYYY, h:mm:ss a') }}

but, it does not appear. It's just a blank. How I can try to use moment in vue?

Momentjs Solutions


Solution 1 - Momentjs

With your code, the vue.js is trying to access the moment() method from its scope.

Hence you should use a method like this:

methods: {
  moment: function () {
    return moment();
  }
},

If you want to pass a date to the moment.js, I suggest to use filters:

filters: {
  moment: function (date) {
    return moment(date).format('MMMM Do YYYY, h:mm:ss a');
  }
}

<span>{{ date | moment }}</span>

[demo]

Solution 2 - Momentjs

If your project is a single page application, (eg project created by vue init webpack myproject), I found this way is most intuitive and simple:

In main.js

import moment from 'moment'

Vue.prototype.moment = moment

Then in your template, simply use

<span>{{moment(date).format('YYYY-MM-DD')}}</span>

Solution 3 - Momentjs

In your package.json in the "dependencies" section add moment:

"dependencies": {
  "moment": "^2.15.2",
  ...
}

In the component where you would like to use moment, import it:

<script>
import moment from 'moment'
...

And in the same component add a computed property:

computed: {
  timestamp: function () {
    return moment(this.<model>.attributes['created-at']).format('YYYY-MM-DD [at] hh:mm')
  }
}

And then in the template of this component:

<p>{{ timestamp }}</p>

Solution 4 - Momentjs

I made it work with Vue 2.0 in single file component.

npm install moment in folder where you have vue installed

<template>
  <div v-for="meta in order.meta">
    {{ getHumanDate(meta.value.date) }}
  </div>
</template>

<script>
    import moment from 'moment';
    export default {
         methods: {
            getHumanDate : function (date) {
                return moment(date, 'YYYY-MM-DD').format('DD/MM/YYYY');
            }
        }
    }
</script>

Solution 5 - Momentjs

Here is an example using a 3rd party wrapper library for Vue called vue-moment.

In addition to binding Moment instance into Vue's root scope, this library includes moment and duration filters.

This example includes localization and is using ES6 module imports, an official standard, instead of NodeJS's CommonJS module system requires.

import Vue from 'vue';

import moment from 'moment';
import VueMoment from 'vue-moment';

// Load Locales ('en' comes loaded by default)
require('moment/locale/es');

// Choose Locale
moment.locale('es');

Vue.use(VueMoment, { moment });

Now you can use the Moment instance directly in your Vue templates without any additional markup:

<small>Copyright {{ $moment().year() }}</small>

Or the filters:

<span>{{ 3600000 | duration('humanize') }}</span>
<!-- "an hour" -->
<span>{{ [2, 'years'] | duration('add', 1, 'year') | duration('humanize') }}</span>
<!-- "3 years" -->

Solution 6 - Momentjs

// plugins/moment.js

import moment from 'moment';

moment.locale('ru');
    
export default function install (Vue) {
  Object.defineProperties(Vue.prototype, {
    $moment: {
      get () {
        return moment;
      }
    }
  })
}
    
// main.js

import moment from './plugins/moment.js';
Vue.use(moment);

// use this.$moment in your components

Solution 7 - Momentjs

For moment.js at Vue 3

npm install moment --save

Then in any component

import moment from 'moment'

...

export default {
  created: function () {
    this.moment = moment;
  },

...

<div class="comment-line">
   {{moment(new Date()).format('DD.MM.YYYY [&nbsp;] HH:mm')}}
</div>

Solution 8 - Momentjs

Moment.js with Vue3 js

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

Main.ts

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

import moment from 'moment'

const app = createApp(App)

app.config.globalProperties.$moment = moment

app.use(router).mount('#app')

Used moments in vue3 js component

{{ $moment(item.created_at).format("YYYY-MM-DD") }}  //	2021-07-03

Solution 9 - Momentjs

> vue-moment

very nice plugin for vue project and works very smoothly with the components and existing code. Enjoy the moments...

// in your main.js
Vue.use(require('vue-moment'));
// and use in component
{{'2019-10-03 14:02:22' | moment("calendar")}}
// or like this
{{created_at | moment("calendar")}}

Solution 10 - Momentjs

global members are not available by default in your <template>'s scope. But you can easily pass them on using computed properties.

computed: {
  moment: () => moment,
  console: () => console,
  window: () => window
}

Now you can use any of them in your template. i.e: console.log(moment(), window).

Note this doesn't add any overhead.

Solution 11 - Momentjs

I'd simply import the moment module, then use a computed function to handle my moment() logic and return a value that's referenced in the template.

While I have not used this and thus can not speak on it's effectiveness, I did find https://github.com/brockpetrie/vue-moment for an alternate consideration

Solution 12 - Momentjs

TESTED

import Vue from 'vue'
    
Vue.filter('formatYear', (value) => {
  if (!value) return ''
  return moment(value).format('YYYY')
})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSet Kyar Wa LarView Question on Stackoverflow
Solution 1 - MomentjsPantelis PeslisView Answer on Stackoverflow
Solution 2 - MomentjsGeng JiawenView Answer on Stackoverflow
Solution 3 - MomentjsPaweł GościckiView Answer on Stackoverflow
Solution 4 - MomentjsmaxView Answer on Stackoverflow
Solution 5 - MomentjsAtchutha rama reddy KarriView Answer on Stackoverflow
Solution 6 - MomentjsRinat SadykovView Answer on Stackoverflow
Solution 7 - MomentjsJiro MatchonsonView Answer on Stackoverflow
Solution 8 - MomentjsMuhammad ShahzadView Answer on Stackoverflow
Solution 9 - MomentjsAwais JameelView Answer on Stackoverflow
Solution 10 - MomentjstaoView Answer on Stackoverflow
Solution 11 - MomentjsCodeFromthe510View Answer on Stackoverflow
Solution 12 - MomentjsNon404View Answer on Stackoverflow