• 时间戳格式化函数


      对时间格式:/Date(1448864369815)/ 的处理

          我们在后台对数据进行json序列化时,如果数据中包含有日期,序列化后的结果可能是这样的: /Date(1448864369815)/  。asp.net mvc 中的 Json() 方法执行后的结果就是如此。

      提供一个原生js的处理方法:

      

        function jsonDateFormat (jsonDt, format) {
                var date, timestamp, dtObj;
    
                timestamp = jsonDt.replace(//Date((d+))//, "$1");
                date = new Date(Number(timestamp));
    
                dtObj = {
                    "M+": date.getMonth() + 1,   //
                    "d+": date.getDate(),        //
                    "h+": date.getHours(),       //
                    "m+": date.getMinutes(),     //
                    "s+": date.getSeconds(),     //
                };
    
           //因为年份是4位数,所以单独拿出来处理
                if (/(y+)/.test(format)) {
                    format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
                }
           
            //遍历dtObj
                for (var k in dtObj) {
              //dtObj的属性名作为正则进行匹配
                    if (new RegExp("(" + k + ")").test(format)) {
                //月,日,时,分,秒 小于10时前面补 0
                        format = format.replace(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+": 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+)/i.test(format)) {
                  format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
           }
           for (var k in date) {
                  if (new RegExp("(" + k + ")").test(format)) {
                         format = format.replace(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'));
  • 相关阅读:
    机器学习-第四讲(模型升级)
    AI人脸匹对
    AI换脸
    人脸识别分析小Demo
    动态规划-线性DP&区间DP
    动态规划-背包问题
    数学知识-博弈论
    数学知识-组合数
    数学知识-扩展欧几里得
    数学知识-欧拉函数&快速幂
  • 原文地址:https://www.cnblogs.com/LiuLiangXuan/p/5756323.html
Copyright © 2020-2023  润新知