制表符读取日期格式的未知文件

Tabulator reading an unknown file with date format

我正在使用一个名为 Tabulator 的 JS 库来读取未知的 tables data/files 所以我从那时起就一直使用这段代码来毫无问题地读取任何未知数据。

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

在大多数情况下效果很好,但后来我尝试输入日期格式的 table(例如 2018-12-12),但输出是纪元时间格式,在现场它应该渲染它渲染的日期格式 1544572800000 我需要它是一种人类可读的格式

是否有办法向代码添加条件以更改列格式,例如列标题为(出生日期)?

看起来你的服务器端有问题,不管是什么提供你的数据,为了一致性我建议修复它,但如果那不可能,那么你有两个选择。

突变体

如果你想改变 table 中的数据,以便它可以以不同的格式导出,你可以设置一个数据 mutator 在列上将此数据映射到更有用的东西。

在此示例中,我们假设它是您正在使用的 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 Documentation

格式化程序

如果您想保持基础数据不变,但只是以不同的方式向用户显示,那么您需要使用 格式化程序.

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

//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}

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

从@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}