ajax解析json数据时,date显示为秒的形式(1511352532000)

一、问题描述:

在jsp页面上通过ajax解析json数据时,发现date类型的数据以秒的形式显示,也就是类似于1511352532000这样的格式。

二、分析:

1511352532000这样的格式是date类型数据的毫秒格式,这就说明是数据的显示格式的问题,由于后台是直接将查询到的对象转为json的,如下:


    @ResponseBody//获取包含了分页后的产品信息
    @RequestMapping(value = "/userSelect/paging", produces = "text/html;charset=UTF-8")
    public String userSelectPaging(String goPage, HttpSession session) {
        int page;
        if (goPage.equals(""))
            page = 0;
        else
            page = Integer.parseInt(goPage);
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        Pageable pageable = new PageRequest(page, 10, sort);
        Page<User> users = userService.findAll(pageable, session);
        return JSON.toJSONString(users, true);
    }

三、解决:

在jsp页面上写一个js函数,如下

 function fmtDate(inputTime) {
        var date = new Date(inputTime);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        var second = date.getSeconds();
        minute = minute < 10 ? ('0' + minute) : minute;
        second = second < 10 ? ('0' + second) : second;
        return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
    }

在需要转换格式的地方直接调用该函数即可,别忘了要传入一个date类型的参数才行奥~~~
如下:

...
trObj += "<td width='20px'>" + fmtDate(page.content[i].createDate) + "</td>";
...

四、结果展示:

这里写图片描述

这里写图片描述

五、写在最后:

But are we all lost stars.Trying to light up the dark~

posted @ 2017-12-03 17:18  晓风残月龙  阅读(155)  评论(0编辑  收藏  举报