Mohammadreza Ahmadpour
Mohammadreza Ahmadpour

Reputation: 111

Convert date format in vue js with laravel

I'm using verta library to convert gregorian dates to hijri date in laravel https://github.com/hekmatinasser/verta

in simple mode (.blade.php files) I'm using code like this:

{{ Verta($category->created_at)->format('%d %B %Y') }}
for converting {{created_at}}

but in Vue js I can't access to this format an I have

{{category.created_at}}

how can I convert the vue js dates with this method?

Upvotes: 5

Views: 12890

Answers (4)

Victor
Victor

Reputation: 1041

You can use vue-moment.

npm install vue-moment

...and require the plugin like so:

Vue.use(require('vue-moment'));

Then, in your application you can do something like this:

{{ someDate | moment("dddd, MMMM Do YYYY") }}

Deprecated in Vue 3

Upvotes: 0

Talha Fayyaz
Talha Fayyaz

Reputation: 302

In Laravel Side

1)
public function getCreatedAtAttribute($value)
{
    return $value->format('d-m-Y');
}

2)protected $casts = [
    'birthday'  => 'date:Y-m-d'
];

In Vue .js side make filters

npm install moment

In  resources/js/app.js

import moment from 'moment';

Vue.filter('formatDate', function(value) {
    if (value) {
        return moment(String(value)).format('MM/DD/YYYY')
    }
});

in Vue component side

{{ category.created_at | formatDate }}

Upvotes: 2

Faridul Khan
Faridul Khan

Reputation: 2007

Simply, You can do it by follow three steps by moment.js.

Step 1:

npm install moment --save

Step 2:

import moment from "moment";

Step 3:

export default {
    data() {
        return {
            moment: moment
        }
    } }

Done.

Now do in below

 {{ moment(category.created_at).format("DD-MM-YYYY") }}

Upvotes: 7

Frnak
Frnak

Reputation: 6792

You can use a mutator on your model to parse the date before returning it.

public function getCreatedAtAttribute($value)
{
    return Verta($value)->format('%d %B %Y');
}

This should be defined on your Category Model

{{category.created_at}}

Will then contain the already parsed date

Upvotes: 1

Related Questions