在 jquery 数据表中显示之前将 json 日期格式化为 mm/dd/yy 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28733613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:31:17  来源:igfitidea点击:

format json date to mm/dd/yy format before displaying in a jquery datatable

jqueryjsondatedatatables

提问by Geo Thomas

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

我想在显示一些数据的数据表,我使用的表脚本

$('#userData').dataTable({

        "ajax": {
                "url": "${rc.getContextPath()}/module/roles/users-list",
                "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

表接收到的数据是 json 并且类似于

[
 {  
      "userId":179,
      "applicationId":"pgm-apn",
      "username":"collaborator.user3",
      "password":"password1",
      "email":"[email protected]",
      "firstName":"Anthony",
      "lastName":"Gonsalves",
      "enabled":true,
      "userCreated":"sitepmadm",
      "userModified":"sitepmadm",
      "createdTime":1422454697373,
      "updatedTime":1422454697373
   },
   {  
      "userId":173,
      "applicationId":"pgm-apn",
      "username":"consumer.user",
      "password":"password1",
      "email":"[email protected]",
      "firstName":"sherlock ",
      "lastName":"homes",
      "enabled":true,
      "userCreated":"sitepmadm",
      "userModified":"sitepmadm",
      "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

我想将日期显示为正确的日期时间。目前它在 json 数据中显示为相同的刺痛。有没有办法在数据表中转换它

回答by nhkhanh

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

您可以使用“渲染”属性来格式化您的列显示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();
    }
}

回答by David Sopko

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

对于可为空的日期时间 DateTime?,您需要使用不同的呈现函数:

        $('#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();}
            }
        ]};

回答by TechnoCrat

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

我已经使用moment js创建了演示,并使用 render 函数将 json 数据转换为所需的格式。

jsfiddle demo

jsfiddle 演示

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();
        }
    }]
});

回答by jinxed_coder

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

在 js 中处理日期时,我总是使用 moment.js( http://momentjs.com/)。

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

返回的日期值在 unix 时间戳中,因此您需要转换它们。

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

这是一个示例小提琴:http: //jsfiddle.net/fws8u54g/

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

回答by Mahfuzur Rahman

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

对于 dot.net 和 javascript,你可以像@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
            },

回答by IamP

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

回答by Suraj Gulhane

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