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

时间:2018-12-03 18:47:37

标签: javascript tabulator

我正在使用一个称为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),但是输出为纪元时间格式,在该字段中应呈​​现为呈现此1544572800000的日期格式,我需要使其成为人类可读的格式

例如,在列标题为(出生日期)的情况下,是否有一种方法可以向代码中添加条件以更改列格式?

2 个答案:

答案 0 :(得分:0)

看来您的服务器端有问题,无论提供数据的是什么,出于一致性考虑,我建议在此修复它,但是如果不可能,则有两种选择。

Mutator

如果您要更改表中的数据以便以其他格式导出,可以在列上设置数据 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

格式化程序

如果您想保留基础数据,但只向用户显示不同的数据,则您要使用 格式化程序

此代码非常类似于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}

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

答案 1 :(得分:0)

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