时间戳格式化函数
  对时间格式:/Date(1448864369815)/ 的处理
我们在后台对数据进⾏json序列化时,如果数据中包含有⽇期,序列化后的结果可能是这样的: /Date(1448864369815)/  。asp mvc 中的 Json() ⽅法执⾏后的结果就是如此。
  提供⼀个原⽣js的处理⽅法:
    function jsonDateFormat (jsonDt, format) {
var date, timestamp, dtObj;
timestamp = place(/\/Date\((\d+)\)\//, "$1");
date = new Date(Number(timestamp));
dtObj = {
"M+": Month() + 1,  //⽉
"d+": Date(),        //⽇
"h+": Hours(),      //时
"m+": Minutes(),    //分
"s+": Seconds(),    //秒
};
       //因为年份是4位数,所以单独拿出来处理
if (/(y+)/.test(format)) {
format = place(RegExp.$1, (FullYear() + "").substr(4 - RegExp.$1.length));
}
      //遍历dtObj
for (var k in dtObj) {
         //dtObj的属性名作为正则进⾏匹配
if (new RegExp("(" + k + ")").test(format)) {
           //⽉,⽇,时,分,秒⼩于10时前⾯补 0
format = place(RegExp.$1, RegExp.$1.length == 1 ? dtObj[k] : ("00" + dtObj[k]).substr(("" + dtObj[k]).length));
}
}
return format;
}
//调⽤
jsonDateFormat("/Date(1448864369815)/","yyyy-MM-dd hh:mm:ss");
或者
Date.prototype.format = function(format) {
var date = {
"M+": Month() + 1,
"d+": Date(),
"h+": Hours(),
"m+": Minutes(),
"s+": Seconds(),
"q+": Math.floor((Month() + 3) / 3),
"S+": Milliseconds()
};
if (/(y+)/i.test(format)) {
format = place(RegExp.$1, (FullYear() + '').substr(4 - RegExp.$1.length));
}
for (var k in date) {
if (new RegExp("(" + k + ")").test(format)) {
format = place(RegExp.$1, RegExp.$1.length == 1
date[k] : ("00" + date[k]).substr(("" + date[k]).length));
正则匹配时间戳
}
}
return format;
}
console.log(newDate.format('yyyy-MM-dd h:m:s'));

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。