正在读取日期格式的未知文件的表格



我正在使用一个名为Tabulator的JS库来读取未知的表数据/文件,所以从那以后我一直使用此代码来读取任何未知的数据,而不会出现任何问题。

var table = new Tabulator("#table", {
data:tableData,
columns:Object.keys(tableData[0]).map(obj => {
return {
title: obj,
field: obj,
sorter: "string",
align: "center",
};
}),
});

它在大多数情况下都很有效,但后来我尝试输入一个日期格式的表(例如2018-12-12(,但输出是epoch时间格式。在它假设呈现日期格式的字段中,它呈现了这个1544572800000,我需要它是一个人类可读的格式

例如,如果列标题是(出生日期(,有没有办法在代码中添加一个条件来更改列格式?

这看起来像是你的服务器端有一个问题,无论是什么提供你的数据,为了一致性,我建议在那里解决它,但如果这不可能,那么你有两个选项。

突变体

如果您想更改表中的数据,使其可以以不同的格式导出,您可以在列上设置数据赋值函数,以将此数据映射到更可用的数据。

在本例中,假设您使用的是date字段,我们将创建一个自定义赋值函数,然后在该列的列定义中分配赋值函数:

//define custom mutator
var dateMutator = function(value, data, type, params, component){
//value - original value of the cell
//data - the data for the row
//type - the type of mutation occurring  (data|edit)
//params - the mutatorParams object from the column definition
//component - when the "type" argument is "edit", this contains the cell component for the edited cell, otherwise it is the column component for the column
//convert date to JS date object
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(value);
//format date to YYYY-MM-DD
var month = '' + (d.getMonth() + 1);
var day = '' + d.getDate();
var year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
//column definition
{title:"Date", field:"date", mutatorData:dateMutator}

关于突变体的更多信息可以在突变体文档中找到

格式化程序

如果您想保持底层数据的原样,但只是以不同的方式向用户显示,则需要使用格式化程序

它的代码与mutator非常相似,我们将再次定义一个自定义函数,然后将其绑定到列定义中的列

//define custom formatter
var dateFormatter = function(cell, formatterParams, onRendered)
//cell - the cell component
//formatterParams - parameters set for the column
//onRendered - function to call when the formatter has been rendered
//convert date to JS date object
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(cell.getValue());
//format date to YYYY-MM-DD
var month = '' + (d.getMonth() + 1);
var day = '' + d.getDate();
var year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
//column definition
{title:"Date", field:"date", formatter:dateFormatter}

有关格式化程序的更多信息,请参阅格式化程序文档

以@Oli Folkerd为例进行了简化。

//define custom mutator
var dateMutator = function(value, data, type, params, component){
return (new Date(value)).toISOString().split('T')[0];
//returns current value as YYYY-MM-DD
}
//column definition
{title:"Date", field:"date", mutatorData:dateMutator}

最新更新