Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Date in MUI DataGrid

How can i format the date data in MUI DataGrid from mongo format to moment.

Also I want to include an extra field with the edit icon which when clicked, would redirect to the edit page

Here's what i have.

 const columns = [

    { field: 'createdAt', headerName: 'Join Date', width: 100 },
    { field: *****, headerName: 'Edit', width: 120 }
]

I get my output as 2022-04-03T09:24:40.199Z. I want to format it using moment.js. how can i achieve this?

Is there a way of including the edit icon and passing the id of the clicked item

Since the field contains the data from the database represented by a string. I have tried template literals. It didn't work as well.

like image 776
merlin Avatar asked Feb 06 '26 22:02

merlin


2 Answers

Try adding valueFormatter property into createdAt field object as shown in the code below. This should solve your problem.

const columns = [
   ...

   { 
     field: 'createdAt', 
     headerName: 'Join Date', 
     width: 100,
     valueFormatter: params => 
     moment(params?.value).format("DD/MM/YYYY hh:mm A"),
   },

   ...
]

You can also find more about DataGrid cell customization in this document:

https://mui.com/x/react-data-grid/column-definition/#rendering-cells

like image 66
Be Munin Avatar answered Feb 09 '26 04:02

Be Munin


For lightweight dayjs you can adopt Be Munin's answer like

const columns = [
   ...

   { 
     field: 'createdAt', 
     headerName: 'Join Date', 
     width: 100,
     valueFormatter: (params) => dayjs(params.value).format('DD/MM/YYYY'),
   },

   ...
]
like image 40
user158 Avatar answered Feb 09 '26 04:02

user158



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!