Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format Vuetify data table date column?

I have a simple data table using Vuetify data table. One of the column is a createdOn (date time), I want to format it. How can I do it ?

This is what i get now:

This is what i get now

<template>
   <v-layout>
      <v-data-table :headers="headers" :items="logs">
      </v-data-table>
   <v-layout>
</template>
<script>
      headers: [
        { text: "Time", value: "createdOn", dataType: "Date" },
        { text: "Event Source", value: "eventSourceName" },
        { text: "Event Details", value: "eventDetails" },
        { text: "User", value: "user" }
      ],
      items: [],
</script>
like image 652
Kavin404 Avatar asked Sep 15 '19 14:09

Kavin404


2 Answers

You should use a custom row cell :

<v-data-table :headers="headers" :items="logs">
  <template v-slot:item.createdOn="{ item }">
    <span>{{ new Date(item.createdOn).toLocaleString() }}</span>
  </template>
</v-data-table>
like image 178
Boussadjra Brahim Avatar answered Oct 23 '22 04:10

Boussadjra Brahim


I found out a way to format cell values using dynamic slot names and a function in the header object:

In the <v-data-table> I did:

<template v-for="header in headers.filter((header) => header.hasOwnProperty('formatter'))" v-slot:[`item.${header.value}`]="{ header, value }">
    {{ header.formatter(value) }}
</template>

and in the vue data property I did:

headers: [
    ...
    { text: 'Value for example', value: '10000', formatter: formatCurrency },
    ...
]

And finally in the methods prop I did:

formatCurrency (value) {
    return '$' + value / 100
},

Here's a sandbox to see it in action: https://codesandbox.io/s/vuetify-datatable-value-formatter-jdtxj

EDIT: In this specific case you could use momentjs or javascript's Date()

like image 45
SneakyLenny Avatar answered Oct 23 '22 04:10

SneakyLenny