5

I am struggling to convert the date-time formate in Vue.js 3. Somehow moment.js not working in Vue 3 version as I see. can anyone help me?

Thanks

vue file

<template>
  <div>
    <p class="text-danger">
      {{ dateTime(category.created_at) }}
    </p>
  </div>
</template>

<script>
import moment from "moment";
export default {
  computed: {
    dateTime(value) {
      return moment(value).format("YYYY-MM-DD");
    },
  },
};
</script>

getting error

http://prntscr.com/10z3p80

3 Answers 3

18

Computed properties don't take arguments, but methods do. You probably either want this:

<template>
  <div>
    <p class="text-danger">
      {{ dateTime(category.created_at) }}
    </p>
  </div>
</template>
<script>
import moment from 'moment';

export default {
  methods: {
    dateTime(value) {
      return moment(value).format('YYYY-MM-DD');
    },
  },
};
</script>

Or something like this:

<template>
  <div>
    <p class="text-danger">{{ formattedDate }}</p>
  </div>
</template>
<script>
import moment from 'moment';

export default {
  computed: {
    formattedDate {
      return moment(this.category.created_at).format('YYYY-MM-DD');
    },
  },
};
</script>

Edit: Corrected spelling

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this using mathods options it's work for me
3

If you prefer the <script setup> way:

<template>
    <div class="">
        <div class=""> {{ moment(date).format("YYYY-MM-DD") }} </div>
    </div>
</template>

<script setup>
import moment from "moment";

let props = defineProps({
    date: String,
});
</script>

Comments

0

You can use filters as well.

<template>
  <div>
    <p class="text-danger">
      {{ category.created_at | dateFormat }}
    </p>
  </div>
</template>

and

filters: {
   dateFormat(date) {
       return moment(date, "YYYY-MM-DD").format("YYYY-MM-DD"); 
   }
}

Important to add format example "YYYY-MM-DD" to moment(date, "YYYY-MM-DD") without format in the first part it returns an Invalid Date in Safari and Firefox but works on Chrome.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.