condor126
condor126

Reputation: 67

How to post-process column values in jQuery DataTables

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

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

                ]
            }
        );

I have the above code to consume some JSON data to populate a table using DataTables (https://datatables.net/). The JSON format is like below: {data: [{t:1459192455326, c:2},{t: 1459192455326, c:3}]}.

So how can I do some post processing of the returned JSON (convert the timestamp to human readable form) in order to render the table?

Upvotes: 0

Views: 578

Answers (1)

CMedina
CMedina

Reputation: 4222

If you want convert timestamp you can use:

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

For use in DataTable you can use render function try...

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

            ]
        }
    );

Result: https://jsfiddle.net/cmedina/7kfmyw6x/30/

Upvotes: 1

Related Questions