Search code examples
javascriptjsonjspspring-bootjqgrid

jqGrid string custom format like date format


I'm trying to print json data on web page with jqGrid, but there are some problems.

Here is my js script code.

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

created_date is json data(origin java String type).

So, I can see created_date on web page grid, like this : 20180912093510, it means 2018/09/12 09:35:10.

The problem is : How can I formatting string type in jqgrid?

I want to see 2018/09/12 09:35:10, not 20180912093510.

I tried first :

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

but it's result was : NaN/NaN/NaN NaN:NaN:NaN

I tried second :

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

but it's result was : 1970/01/01 00:00:00

Can I convert string data to date-like data? Must make string-formatting function? If I can, please give some examples.


Solution

  • You can use, for example, custom formatter, which calls predefined date-formatter internally. The corresponding code could look like the following:

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

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