JavaScript中JSON类型的日期格式转换(Ajax)

来源:互联网 发布:国家护理数据平台 编辑:程序博客网 时间:2024/06/06 07:31

在使用JSON传递日期格式后,有时候直接取得的日期会发现无法正常显示。这个时候需要我们对取到的值进行进一步加工处理。
一、直接调用JSON方法,对数据进行封装后传递的取值:
1、对日期进行JSON保存

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception{    java.util.Date now= new  java.util.Date();    JSONObject js = new JSONObject();    js.put("now",now);    response.getWriter().print(js);}

2、在js中提供一个公共的日期转换方法:

    // 对Date的扩展,将 Date 转化为指定格式的String    // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,     // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)     // 例子:     // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423     // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18     Date.prototype.format = function(fmt) {        var o = {            "M+" : this.getMonth() + 1, //月份             "d+" : this.getDate(), //日             "h+" : this.getHours(), //小时             "m+" : this.getMinutes(), //分             "s+" : this.getSeconds(), //秒             "q+" : Math.floor((this.getMonth() + 3) / 3), //季度             "S" : this.getMilliseconds()        //毫秒         };        if (/(y+)/.test(fmt))            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")                    .substr(4 - RegExp.$1.length));        for ( var k in o)            if (new RegExp("(" + k + ")").test(fmt))                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])                        : (("00" + o[k]).substr(("" + o[k]).length)));        return fmt;    } 

3、对日期进行相应的转换:
假设data是返回的JSON对象

console.log("要显示的日期时间是"+new Date(data.now.time).format("yyyy-MM-dd"));

二、直接返回对象,在Java中不执行JSON包装
详细代码参考:http://blog.csdn.net/u012737182/article/details/52830596

@RequestMapping(value="/member/{mid:\\d+}",method=RequestMethod.GET,produces="application/json;charset=UTF-8")    public @ResponseBody Object get(@PathVariable("mid") int mid){        log.info("要查看的是:"+mid);        Emp vo = new Emp();        vo.setEmpno(mid);        vo.setEname("SMITH");        vo.setSal(1.1);        vo.setHiredate(new Date());        return vo;    }

js中:

$(getBut).on("click",function(){        $.ajax({            url: "member/1",            method : "get" ,            data : {            },            dataType : "json",            success : function(data){                $(showDiv).append("<p> 编号:"+data.allMembers.empno+",名称:"+data.allMembers.ename+",工资"+                        data.allMembers.sal+",日期:"+new Date(data.emp.hiredate).format("yyyy-MM-dd")+"</p>");            },            error : function(data){                $(showDiv).append("<p>出错了</p>");            }        })    });

总结:
如果有在代码中有进行JSON封装保存的,在取值的时候需要用.time取得对应的日期数值内容,如果代码中没有进行JSON保存,而是自动封装的,则直接调用即可。

0 0
原创粉丝点击