Moment.js with Vuejs
Asked Answered
N

14

185

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?

Noles answered 16/12, 2015 at 9:16 Comment(0)
T
294

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]

Tychon answered 16/12, 2015 at 11:18 Comment(7)
if using es6, dont forget - import moment from 'moment';Bally
Filters are disabled in Vue 2+. You should use a computed property instead. See my answer to this question.Lavonda
For Vue v2 you can use global filter vuejs.org/v2/api/#Vue-filterRobles
Quick clear answer that works in a component. Respect.Gilles
@PawełGościcki are you sure about filters not working in Vue2? because for me they doAlthorn
with spread operator: moment(...args) { return moment(...args); }Mareld
Filters are being deprecated in Vue 3. I've been using this method for a while now and now working on replacing quite a bit of code in preparation for updating to Vue 3. v3.vuejs.org/guide/migration/filters.html#overviewTimeconsuming
N
187

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>
Nel answered 30/3, 2017 at 8:58 Comment(4)
Should also work for other application types aside from SPAs.Allred
I really like this method of using Moment. Thanks for sharing! I've just implemented it but with a small change as suggested in the docs, Vue.prototype.$moment = moment. vuejs.org/v2/cookbook/adding-instance-properties.html.Timeconsuming
Simple but you can't have type recognition in VS code.Contreras
This worked for me. I'm using Laravel mix with Vue 2.6.12 in my Laravel app. Thanks @Geng JiawenMuckrake
T
40

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>
Trainload answered 5/11, 2016 at 11:42 Comment(1)
It's worth noting that if, instead of using a parameter-less function, you want to use a function like: date2day: function (date) {return moment(date).format('dddd')} You cannot use computed, and should use methods instead.Atwater
D
21

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>
Durning answered 24/12, 2016 at 11:42 Comment(2)
Why method, why not computed?Steelyard
For display purposes, I used method. Feel free to use computed property.Durning
M
9

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" -->
Metzgar answered 2/5, 2019 at 6:36 Comment(1)
FYI: This answer was flagged as low-quality because of its length and content. You may want to improve it by explaining how this answers OP's question.Kearney
B
8
// 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
Brewer answered 4/3, 2020 at 6:5 Comment(1)
Nice use of plugins to isolate moment-related stuff in a separate file. Works great!Inwrought
M
6

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>
Moreen answered 4/1, 2021 at 22:43 Comment(1)
Just use computed: { moment: () => moment }. See my answer.Vanhoose
I
6

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
Incite answered 5/7, 2021 at 7:58 Comment(0)
T
1

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")}}
Timbale answered 4/10, 2019 at 11:11 Comment(0)
V
1

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.

Vanhoose answered 5/1, 2021 at 0:54 Comment(0)
G
1

I've read the solutions posted here and it seems to be more complex than my solution so I'm presenting this one, what I do is like this

The thing you need:

import moment from 'moment';
...
data() {
  return {
    moment: moment, // This is the one line of code that you need
  }
}

So this is what it looks like

HTML (Now this works):

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

JS:

import moment from 'moment';

export default {
  data() {
    return {
      moment: moment, // This is the one line of code that you need
    }
  }
}
Gravitative answered 14/8, 2022 at 9:9 Comment(0)
C
0

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

Chymotrypsin answered 20/2, 2019 at 9:29 Comment(0)
V
0

TESTED

import Vue from 'vue'
    
Vue.filter('formatYear', (value) => {
  if (!value) return ''
  return moment(value).format('YYYY')
})
Villon answered 7/12, 2020 at 10:47 Comment(0)
L
0

Install the moment module:

npm i moment

In your vue component:

import moment from 'moment';
export default {
   data(){

   },
   methods:{
     moment(date){ return moment(date) }
   }
}

Inside the template:

<span>{{ moment().format('MMMM Do YYYY, h:mm:ss a') }}</span>
Lowborn answered 11/12, 2022 at 15:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.