处理返回的Json时间字段中带T
在时间和日期之间会帮我们加个字母大些T,那如何解决呢?
第一种:提前在后端返回数据时进行格式化。
将datetime类型转换成string类型,不要以datetime类型进行json序列化,这样可以避免问题。
第二种:在前端通过js进行格式化。
首先我们扩展new Date的方法:pattern
Date.prototype.pattern = function (fmt) { var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时 "H+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; var week = { "0": "\u65e5", "1": "\u4e00", "2": "\u4e8c", "3": "\u4e09", "4": "\u56db", "5": "\u4e94", "6": "\u516d" }; if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); } if (/(E+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]); } 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; };
在调用时:
var createTime="2017-09-05T13:08:56.080";
var date=new Date(createTime.replace('T', " ")).pattern("yyyy-MM-dd hh:mm:ss")
说明:先将字符T替换成“ ”空格,也就是时间2017-09-05 13:08:56.080,然后再进行格式化,转换自己需要的格式:yyyy-MM-dd hh:mm:ss
posted on 2019-03-16 23:35 Denghejing 阅读(1028) 评论(0) 收藏 举报
浙公网安备 33010602011771号