Best way to format date without moment js in vue2?

Hi all,

Let’s say you have a date like this in a loop:

<span v-for="item in data">
<small>{{item.created_at }}</small>

item.created_at outputs: 2021-11-22 16:32:52

I would like to format it to: 22-11-2021

How can I do this in a loop without using moment.js please?

Thank you,

There are all sorts of Date methods, but formatting is a bit trickier. Have a read of this: Everything You Need to Know About Date in JavaScript | CSS-Tricks

Or just use a lib like date-fns or Dayjs if you plan to do a lot of formatting. No point in re-inventing the wheel.

1 Like

Beautiful link, thank you so much for this. I bookmarked it!
Someone else told me to use this:

Any experience with this library please?


Yes, it’s a good lib. It’s basically Moment.js (essentially the same API), but done with modern JS.

Yes this can be achieved without momentjs, dayjs or any other library. Built in Date object is sufficient in order to achieve this.
You may want to use filters in this case in order to format.
Just add filter

filters: {
    formatDate(dateToBeFormatted) {
        const date = new Date(dateToBeFormatted);
        return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;

Note: date.getMonth() returns month starting from 0, so 0 → January, 10 → November, so adding +1 to date.getMonth() will give you desired result.

I wouldn’t recommend using filters. They’ve been dropped in Vue 3 in favour of just using functions which is a much more flexible and testable approach.

1 Like