18

I am trying to display some data in a datatable and the table script I am using is

$('#userData').dataTable({
     
        "ajax": {
                "url": "my-url",
                "dataSrc":  "",
                },
                
        "columns":[
        {"data": "userId"},
        {"data": "applicationId"},
        {"data": "username"},
        {"data": "firstName"},
        {"data": "userCreated"},
        {"data": "createdTime"},
        {"data": "updatedTime"}
        ],
        
     });

the data that is received by the table is json and would be something like

[
 {  
      "userId":179,
      "applicationId":"pgm-apn",
      "username":"collaborator.user3",
      "password":"password1",
      "email":"[email protected]",
      "firstName":"Anthony",
      "lastName":"Gonsalves",
      "enabled":true,
      "userCreated":"gtuser",
      "userModified":"gtuser",
      "createdTime":1422454697373,
      "updatedTime":1422454697373
   },
   {  
      "userId":173,
      "applicationId":"pgm-apn",
      "username":"consumer.user",
      "password":"password1",
      "email":"[email protected]",
      "firstName":"sherlock ",
      "lastName":"homes",
      "enabled":true,
      "userCreated":"gtuser",
      "userModified":"gtuser",
      "createdTime":1422010854246,
      "updatedTime":1422010854246
   }

I want to display the dates as proper datetime.Currently it is getting displayed as teh same sting in the json data.Is there any way to convert that in the datatable

8 Answers 8

53

You can use "render" property to format your column display http://datatables.net/reference/option/columns.render#function.

For example:

{
    "data": "createdTime",
    "render": function (data) {
        var date = new Date(data);
        var month = date.getMonth() + 1;
        return (month.toString().length > 1 ? month : "0" + month) + "/" + date.getDate() + "/" + date.getFullYear();
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

This works ...thanks ....is there a way I can get the date in the following format '02/12/2015 18:26 23'.....with the exact time
Check out date.getHours(), date.getMinutes(), date.getSeconds().
if month .length > 1 then also add "0" in my code for eg - if month is 10 or 11 or 12 then it show 010 or 011 or 012
23

For a nullable date time, DateTime?, you will want to use a different rendering function:

        $('#userData').DataTable({
        columns: [
            { "data": "userId"},
            {"data": "userCreated",
             "type": "date ",
             "render":function (value) {
                 if (value === null) return "";

                  var pattern = /Date\(([^)]+)\)/;
                  var results = pattern.exec(value);
                  var dt = new Date(parseFloat(results[1]));

                  return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();}
            }
        ]};

Comments

6

i have created demo using moment js and use of render function to convert json data into required format.

jsfiddle demo

also find code below:

testdata = [{
    "id": "58",
        "country_code": "UK",
        "title": "Legal Director",
        "pubdate": "1422454697373",
        "url": "http://..."
}, {
    "id": "59",
        "country_code": "UK",
        "title": "Solutions Architect,",
        "pubdate": "1422454697373",
        "url": "http://..."
}];

$('#test').dataTable({
    "aaData": testdata,
        "aoColumns": [{
        "mDataProp": "id"
    }, {
        "mDataProp": "country_code"
    }, {
        "mDataProp": "title"
    }, {
        "mDataProp": "pubdate"
    }, {
        "mDataProp": "url"
    }],
        "columnDefs": [{
        "targets": 3,
            "data": "pubdate",
            "render": function (data, type, full, meta) {
                console.log('hi...');
            console.log(data);
                console.log(type);
                console.log(full);
                console.log(meta);
            return moment.utc(data, "x").toISOString();
        }
    }]
});

Comments

3

{
  "render": function (data) {
              var d = new Date(data);
              return d.toLocaleString();
}

Comments

2

For dot.net and javascript, you can just use like @David Sopko

 {
                "data": "Date", "type": "date ",
                "render": function (value) {
                    if (value === null) return "";
                    var pattern = /Date\(([^)]+)\)/;//date format from server side
                    var results = pattern.exec(value);
                    var dt = new Date(parseFloat(results[1]));

                    return dt.getDate() + "." + (dt.getMonth() + 1) + "." + dt.getFullYear();
                }, "autoWidth": true
            },

Comments

2

For showing the time along with the date add the code below:

"data": 'Date' , 
                        "render": function (data) {
                            var date = new Date(data);
                            var month = date.getMonth() + 1;
                            return (month.length > 1 ? month : "0" + month) + "/" + date.getDate() + "/" + date.getFullYear() + "&nbsp;&nbsp;" +(date.getHours() < 10 ? ("0"+date.getHours()) : date.getHours())+ ":"+(date.getMinutes() < 10 ? ("0"+date.getMinutes()) : date.getMinutes()) ; 
                            //return date;
                        }

Comments

1

I always use moment.js(http://momentjs.com/) when dealing with dates in js.

The date values returned are in unix timestamp so you need to convert them.

Here's a sample fiddle: http://jsfiddle.net/fws8u54g/

var created = 1422010854246;
moment.utc(created, "x").toISOString();

Comments

1

@Suraj Gulhane --your answer is the only one I could get to work for ASP.NET Core Server-Side jQuery DataTables DateTime formatting.

I customized it a little (essentially removing the time, putting year first) but here's what that looks like in case it helps anyone else:

{
  "data": "dateOfBirth", "name": "Date Of Birth", "type": "date",
  "render": function (data) {
    var date = new Date(data);
    var month = date.getMonth() + 1;
    var day = date.getDate();
    return date.getFullYear() + "/" 
       + (month.length > 1 ? month : "0" + month) + "/" 
       + ("0" + day).slice(-2);
       //return date format like 2000/01/01;
    }, "autoWidth": true
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.