JavaScript中JSON型別的日期格式轉換(Ajax)
阿新 • • 發佈:2019-01-02
在使用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"));
@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儲存,而是自動封裝的,則直接呼叫即可。