How to format date in ant table? - javascript

I have a table with 6 columns, one of these columns is a date, The default display format of the date is 2020-04-30T21:30:07.000Z I want to change it to 30-04-2020.
export const columns = [
{ title: `ID`, dataIndex: `invoice_id`},
{ title: `Invoice Number`, dataIndex: `invoice_number` },
{ title: `Amount`, dataIndex: `invoice_amount`},
{ title: `Store Name`, dataIndex: `store_name`},
{ title: `Supplier Name`, dataIndex: `supplier_name`},
{ title: `Creation Date`, dataIndex: `invoice_date`,},
]
<Table bordered columns={columns} dataSource={invoices_list} />
I believe there should be a way to pass date format to the columns. I looked into the ant table documentations but didn't find a solution.

Another way to implement it is to define a 'render' for a date column like
{
title: 'Published at',
dataIndex: 'publishedAt',
key: 'publishedAt',
width: 210,
render: ((date:string) => getFullDate(date)) }
and just utilize date formatting function getFullDate. In your case it can look like
export const getFullDate = (date: string): string => {
const dateAndTime = date.split('T');
return dateAndTime[0].split('-').reverse().join('-');
};
In this case you'll also avoid using external libraries and will have a function to format the date in other places.

After looking into the antd documentation (https://ant.design/components/table/#API) it doesn't seems to have a property to handle your case. You should duplicate your column invoices_date to invoices_date_printabble which will have the good format to be printed.
invoices_list.map(el => {
let date = new Date(el.invoices_date)
el.invoices_date_printabble = date.getDay()+"/"+date.getMonth()+"/"+date.getFullYear()
})
And now your list is printable.
export const columns = [
{ title: `ID`, dataIndex: `invoice_id`},
{ title: `Invoice Number`, dataIndex: `invoice_number` },
{ title: `Amount`, dataIndex: `invoice_amount`},
{ title: `Store Name`, dataIndex: `store_name`},
{ title: `Supplier Name`, dataIndex: `supplier_name`},
{ title: `Creation Date`, dataIndex: `invoices_date_printabble`},
]
<Table bordered columns={columns} dataSource={invoices_list} />

Another way to do it using moment.js library.
First install moment.js into your project
npm i moment
Second import it to your component
import moment from 'moment';
Third change date format:
let invoices=response.data
invoices.map(el => {
let date = moment(new Date(el.invoice_date));
el.invoice_date = date.format("DD/MM/YYYY")
})

this worked for me!
export const columns = [
{
title: "ID",
key: "key",
render: (record) => {
return (
<div>
<p>{moment(record.invoice_id).format("DD-MM-YYYY")}</p>
</div>
);
},
},
]

I think the easiest way would be to use moment.js in the render method of the column options:
Your moment format of your existing date can be found in the moment documentation.
For future reference you can always use a millisecond timestamp and convert to whatever date format you want with moment.
export const columns = [
....
{ title: "Creation Date",
dataIndex: "invoices_date",
render: (invoice_date) => { return (<p>{moment(invoices_date, **"Moment Format"**).format(DD-MM-YYYY)}</p>)},
]

Related

How to I change my react table accesssor value based on data conditionally?

const data = {
name:"test1",
fclPrice:100,
lclPrice:null,
total:"50"
}
and my two columns:
const Datatable = [
{ Header: 'Name', accessor: 'name' },
{ Header: 'Price', accessor:'?' },
{ Header: 'Total', accessor:'total' }
];
I want accessor to take the price key which has number
For eg : if fclprice:null and lclPrice:100 it should take lclPrice and viceversa
You can a set a value of an accessor to a function which will take as a first argument the object with your data. Then, you can pass whatever condition you want to it:
const Datatable = [
{ Header: 'Price', accessor: (data)=>data.fclPrice || data.lclPrice},
];

API JSON formatting to bootstrap-vue table

I am a student working on a VueJS dashboard displaying scientific research data from clinicaltrials.gov. The issue is the JSON response value is in the form of an array and as such prints with brackets and quotation marks in the table. I am trying to display the data without the brackets and quotations. In addition, when there are multiple items as in the Condition field, I am trying to display each item seperated by commas.
The data comes from the API as an axios response in the following format:
{
"StudyFieldsResponse":{
"APIVrs":"1.01.02",
"DataVrs":"2021:03:18 22:20:36.369",
"Expression":"Pfizer",
"NStudiesAvail":371426,
"NStudiesFound":5523,
"MinRank":1,
"MaxRank":1,
"NStudiesReturned":1,
"FieldList":[
"OrgFullName",
"Acronym",
"InterventionName",
"Condition",
"Phase",
"LastKnownStatus",
"ResultsFirstPostDate",
"LastUpdatePostDate"
],
"StudyFields":[
{
"Rank":1,
"OrgFullName":[
"Pfizer"
],
"Acronym":[],
"InterventionName":[
"Infliximab [infliximab biosimilar 3]"
],
"Condition":[
"Crohn's Disease",
"Ulcerative Colitis"
],
"Phase":[],
"LastKnownStatus":[],
"ResultsFirstPostDate":[],
"LastUpdatePostDate":[
"December 21, 2020"
]
}
]
}
}
Axios Call in mounted:
var APIurl = "https://clinicaltrials.gov/api/query/study_fields?expr=" + TrialSearch + "%0D%0A&fields=OrgFullName%2CAcronym%2CInterventionName%2CCondition%2CPhase%2CLastKnownStatus%2CResultsFirstPostDate%2CLastUpdatePostDate&min_rnk=1&max_rnk=999&fmt=json"
axios
.get(APIurl)
.then(response => {this.items = response.data.StudyFieldsResponse.StudyFields})
.catch(function (error) {
//eslint-disable-next-line no-console
console.log(error);
})
HTML of b-table:
<b-table :items="items" id="table-list" responsive :per-page="perPage" :current-page="currentPage" :fields="fields" :sort-by.sync="sortBy" :sort-desc.sync="sortDesc" >
</b-table>
js data function:
data: function() {
return {
sortBy: 'name',
perPage: 10,
PipeperPage: 5,
currentPage: 1,
sortDesc: false,
sortByFormatted: true,
filterByFormatted: true,
sortable: true,
fields: [
{ key: 'Acronym', sortable: true },
{ key: 'InterventionName', sortable: true },
{ key: 'Condition', sortable: true },
{ key: 'Phase', sortable: true },
{ key: 'LastKnownStatus', sortable: true },
{ key: 'ResultsFirstPostDate', sortable: true },
{ key: 'LastUpdatePostDate', sortable: true },
],
items: [],
screenshot of current table format
Sorry for the long post; I am really trying to learn but am lost.
Like you said all the properties of the response are arrays instead of primitives values like string, boolean, or number. b-table expects that the items data is an array of rows (that is good) with properties and primitives values like you are passing arrays is printing the whole value as a string.
What you need to do is add a computed property (that will change when items change) mapping that item with a new item, choosing the values you use (to keep it simple) and joining the array in a string.
You can choose to join the array arr.join(', ') or to select the first item arr[0] || "".
Life example https://codesandbox.io/s/api-json-formatting-to-bootstrap-vue-table-r91cw?file=/src/components/Dashboard.vue:1095-1586
<template>
<b-table
:items="simpleItems"
id="table-list"
responsive
:per-page="perPage"
:current-page="currentPage"
:fields="fields"
:sort-by.sync="sortBy"
:sort-desc.sync="sortDesc"
/>
</template>
<script>
export default {
data() {
return {
// your data
}
},
computed: {
simpleItems() {
return this.items.map((item) => {
return {
Acronym: item.Acronym.join(", "),
InterventionName: item.InterventionName.join(", "),
Condition: item.Condition.join(", "),
Phase: item.Phase.join(", "),
LastKnownStatus: item.LastKnownStatus.join(", "),
ResultsFirstPostDate: item.ResultsFirstPostDate.join(", "),
LastUpdatePostDate: item.LastUpdatePostDate.join(", "),
};
})
},
}
}
</script>

Dynamic lookup from React's state in material-table

I'm using the material-table component, which I fill with dynamic data coming from Redux (an array of objects), but then I do other things with that data inside my component's state. To create column dropdown filters, there's an element inside each column's array of options, lookup, that receives an object and creates the dropdown based on it's values.
I am extracting some items from my data and putting them inside an element in my component's state. This is an object, the same kind that lookup receives. The thing is that the component shows an empty dropdown, as if the object was empty, but it's not. I'm logging it in into the console and the object is filled with the data I need.
I initially thought it was a render problem, that the object is empty at the beggining, and then it's filled with data, but the component renders every time.(Yeah, React is reactive).
This is only the code needed to help me solve this problem:
Table component
import React, { Component } from "react";
import MaterialTable from "material-table";
class CustomTable extends Component {
state = {
column1: "",
column2: "",
column3: "",
column1FilterList: {}
columns: [
{
title: "Column1",
field: "column1",
editable: "onAdd",
filtering: true,
lookup: { ...this.column1FilterList }
},
{
title: "Column2",
field: "column2",
editable: "onAdd",
filtering: true,
},
{
title: "Column3",
field: "column3",
editable: "onAdd",
filtering: true
}
]
};
componentDidMount() {
this.props.fetchValues()
this.props.fetchApplications()
this.filterColumn1ExistingKeys()
}
filterColumn1ExistingKeys = () => {
return this.props.elements.map(element => {
return this.setState(prevState => ({
column1FilterList: {
...prevState.column1FilterList,
[element.name]: element.name
}
}))
})
}
render() {
return (
<div>
<MaterialTable
options={{
search: false,
actionsColumnIndex: 4,
filtering: true
}}
title="Search by"
columns={this.state.columns}
data={this.state.data}
/>
</div>
);
}
}
export default CustomTable;
The problem is how you save that data. You create a new object in the constructor with { ...this.column1FilterList }. This will create a new object which will act as the lookup object, which is filled with the initial data of column1FilterList (empty). Updating the column1FilterList later does not change that lookup object, because it is disconnected (new object). You have to update the lookup within the columns as well like this:
const filterColumn1ExistingKeys = () => {
const column1FilterList = this.state.column1FilterList;
this.props.elements.forEach(element => column1FilterList[element.name] = element.name)
this.setState({
column1FilterList,
columns: [{
title: "Column1",
field: "column1",
editable: "onAdd",
filtering: true,
lookup: { ...column1FilterList }
},
{
title: "Column2",
field: "column2",
editable: "onAdd",
filtering: true,
},
{
title: "Column3",
field: "column3",
editable: "onAdd",
filtering: true
}
]
})
}
Hope this helps. Let me know, if that works for you. If you have any questions, let me know. Happy coding.

How to save value in correct format if I received it by getEditor from Ext.form.field.Date?

I use plugin Ext.ux.form.DateTimeField for Extjs and standart Ext.form.field.Date to edit defferent cells in grid according to special parameters in other column. Here is an example:
var myOwnGrid = {
xtype: 'gridpanel',
store: myOwnStore,
...
columns: [
{xtype: 'gridcolumn',
dataIndex: 'mainParamValues',
text: 'MyValues',
...
getEditor: function(record){
switch(record.raw.mainParamNames){ //accourding to value from other column
case "date":
return Ext.create('Ext.grid.CellEditor', {
field: Ext.create('Ext.form.field.Date', {
value: record.raw.mainParamValues,
format: 'Ymd',
altFormats: 'Ymd',
emptyText: "Empty field!"
})
});
}
}
}]
}
When I press on cell and edit, it has correct format for me (20141212 for example). After I press enter or produce other action to save this value, it is automatically formated to "Fri Dec 12 2014 00:00:00 GMT+0300 (MSK)". I have to use these data after editing of full form, so I need 'Ymd' format. Any ideas how to fix such behaviour?
You do not specify default renderer for this field type
{
xtype: 'gridcolumn',
dataIndex: 'mainParamValues',
text: 'MyValues',
...
renderer: Ext.Function.bind(renderCell, this)
}
...
function renderCell(val, meta, rec, rowIndex, colIndex) {
var mainParamNames = 'date'; // your code by record
switch (mainParamNames) {
case "date":
return Ext.util.Format.date(val, 'Y.m.d');
}
}
Fiddle

Formatting of values in dynamic Kendo grid

I am trying to figure out how to format individual values in a Kendo grid bound to a dynamic data source.
The challenge is that the columns are not fixed and the format is not even consistent throughout the column.
From what I can tell Kendo supports format strings at the column level using
columns:[{field:Name,format:{1:c}}]
However this solution is not suitable since it sets the format for the entire column.
I have also found a template based solution that lets you format your data manually using notation like this
columns:[{field:Name,template: "#= kendo.toString(kendo.parseDate(SomeDate, 'yyyy-MM-dd')}]
However, again this is too hard coded for me since it assumes a single type in the column.
I am looking for a way to specify in the data source itself what the type a value is. Is that possible?
Something like this
data = [{field:SomeField,Value:4,Format:{1:c}}]
It turns out you can solve this with a custom template. This will run formatting on every value.
for (var c = 0; c < grid.Cols.length; c++) {
grid.Cols[c].template = "#= FormatValue(" + grid.Cols[c].field + ")#";
}
function FormatValue(value) {
return kendo.toString(value, "c0")//currency formatting
}
If you are going to bind dynamic data source then there in no need to format value in column or feilds. It will automatic adjust with the data.
You should use this pattern
fields: {
EventID: { editable: true, nullable: false },
EventName: { validation: { required: true} },
UserID: { validation: { required: true} },
EventDate: { validation: { required: true} },
EventTimeFrom: { validation: { required: true} },
EventTimeTo: { validation: { required: true} }
}
columns: [
{ field: "EventID", title: "Event ID" },
{ field: "EventName", title: "Event Name" },
{ field: "UserID", title: "User ID" },
{ field: "EventDate", title: "Event Date" },
{ field: "EventTimeFrom", title: "Start Time" },
{ field: "EventTimeTo", title: "End Time" },
],

Categories

Resources