How can I use moment.js to format a date with vue.js?

Viewed 3050

I use a cdn for momentjs and I try to format my date and time

    @{{ process_photo.created_at.moment().format("Do MMM YYYY") }}

1 Answers

To use momentjs in the template, you'd have to use it indirectly through a component method. For example, you could declare a formatDate method that returns the moment.format() results, and use formatDate in the template:

new Vue({
  el: '#app',
  data() {
    return {
      process_photo: {
        created_at: new Date()
      }
    }
  },
  methods: {
    formatDate(date) {
      return moment(date).format("Do MMM YYYY")
    }
  }
})
<script src="https://unpkg.com/vue@2.6.11">
</script>
<script src="https://unpkg.com/moment@2.26.0/moment.js"></script>

<div id="app">
  <p>@{{ formatDate(process_photo.created_at) }}</p>
</div>

Related