首页 > 解决方案 > jqGrid 字符串自定义格式,如日期格式

问题描述

我正在尝试使用 jqGrid 在网页上打印 json 数据,但存在一些问题。

这是我的js脚本代码。

$('#sometables').jqGrid({
    ...
    ...
    ...
    colNames: ['created_date'], 
    colModel: [ {name: 'created_date', align: 'center} ], 
    ...
    ...
    ...
});

created_date是 json 数据(起源 java String 类型)。

所以,我可以created_date在网页网格上看到,像这样 : 20180912093510,这意味着 2018/09/12 09:35:10。

问题是:如何在 jqgrid 中格式化字符串类型?

我想看看2018/09/12 09:35:10,没有20180912093510

我先试过:

{name: 'created_date', align: 'center', formatter: 'date', formatoptions: {newformat: 'Y/m/d H:i:s'}},

但结果是:NaN/NaN/NaN NaN:NaN:NaN

我尝试了第二个:

{name: 'created_date', align: 'center', formatter: 'date', formatoptions: {srcformat: 'string', newformat: 'Y/m/d H:i:s'}},

但结果是:1970/01/01 00:00:00

我可以将字符串数据转换为类似日期的数据吗?必须制作字符串格式化功能吗?如果可以,请举一些例子。

标签: javascriptjsonjspspring-bootjqgrid

解决方案


例如,您可以使用自定义格式化程序,它在内部调用预定义的日期格式化程序。相应的代码可能如下所示:

{
    name: "created_date",
    align: "center",
    sorttype: "integer",
    formatter: function (cellValue, options, rowdata, action) {
        var fixedValue = cellValue.substr(0, 4) + "-" +
                cellValue.substr(4, 2) + "-" +
                cellValue.substr(6, 2) + "T" +
                cellValue.substr(8, 2) + ":" +
                cellValue.substr(10, 2) + ":" +
                cellValue.substr(12);
        return $.fn.fmatter.call(this, "date", fixedValue, options, rowdata, action);
    },
    formatoptions: {
        srcformat: "ISO8601Long",
        newformat: "Y/m/d H:i:s"
    }
}

https://jsfiddle.net/OlegKi/7pzy2x86/1/


推荐阅读