如何在jQuery DataTables中后处理列值

时间:2016-03-28 19:21:26

标签: javascript jquery datatables

        var table = $('#data-table').DataTable(
            {
                ajax: {
                    type: 'GET',
                    url: '/temperature'

                },
                bFilter: false,
                "bLengthChange": false,
                aaSorting: [],
                columns: [
                    {data: "t"},
                    {data: "c"}

                ]
            }
        );

我有上面的代码使用一些JSON数据来使用DataTables(https://datatables.net/)填充表。 JSON格式如下:     {data: [{t:1459192455326, c:2},{t: 1459192455326, c:3}]}

那么如何对返回的JSON进行一些后期处理(将时间戳转换为人类可读的形式)以呈现表格呢?

1 个答案:

答案 0 :(得分:1)

如果您想要转换时间戳,可以使用:

function TimestampToDate(unix_timestamp){
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();

// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);

return formattedTime;
}

要在DataTable中使用,您可以使用render函数试试...

var data = [{t:1459192455326, c:2},{t: 1459192455326, c:3}];

var table = $('#example').DataTable(
        {
            data : data,
            bFilter: false,
            "bLengthChange": false,
            aaSorting: [],
            columns: [
                {data: "t",
                "render": function( oObj ) {
                       return TimestampToDate(oObj);
        } },
                {data: "c"}

            ]
        }
    );

结果:https://jsfiddle.net/cmedina/7kfmyw6x/30/