js時間格式化

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   sp   java   for   

前言:

  js雖然提供了各種擷取時間Date對象的不同屬性方法,如:getDate 方法 | getDay 方法 | getFullYear 方法 | getHours 方法 ... ... 等等,但是卻沒有像java那樣提供一個方法來供使用者來根據自身提供的模板(pattern),來格式化指定時間對象,所以自己就封裝了一個小方法,只供大家閑來調侃-.-,有好的建議還望慷慨指薦哦。

 用到知識點:

  •  arguments:該對象代表正在執行的函數和調用它的函數的參數。不可顯式建立,雖然有length屬性,且能像數組一樣以“[]”文法方式取值,但它並不是一個數組。
  •  typeof object :運算子,返回一個用來表示運算式的資料類型的字串。六種可能: "number," "string," "boolean," "object," "function," 和 "undefined."。
  •    object.constructor:表示建立對象的函數。object必須是對象或函數的名稱。基礎資料沒有該屬性。
  •    exec 方法:用Regex模式在字串中運行尋找,並返回包含該尋找結果的一個數組。沒有找到匹配,則它返回 null。數組中同類型匹配元素不會重複出現。
  •    str.split(Rex|str):以一個正則對象或子字串,將一個字串分割為子字串,然後將結果作為字串數組返回。
  •    throw Error(‘msg‘):拋出一個帶有Message資訊的Error。throw 後面可跟任何錶達式。
  •    還有一些for..in用法,三目運算子,substr這些就不講了,比較簡單。

 程式碼片段:

/** * ***js時間日期格式化*** <br> * <p> * 模版字串採用嚴謹格式,超出則會拋出異常,且每類格式只可出現一次,如:yyyy-mm-yyyy 格式會拋異常 * </p> * y-年    length: 2/4位 <br> * q-季度    length: 1位 <br> * M-月    length: 1~2位 <br> * d-日    length: 1~2位 <br> * H-時    length: 1~2位24小時制,h:12小時制 <br> * m-分    length: 1~2位 <br> * s-秒    length: 1~2位 <br> * S-毫秒 length: 固定1位 * @param {Date類型對象} date * @param {String類型模板字串} fmt * @return 格式化後時間日期文字 * @author lyt * blongs: http://www.cnblogs.com/liuyitian/ */function DateFormat(date, fmt){    if (arguments.length != 2) // 參數個數校正        throw Error(‘arguments長度不合法‘);    if (!date || (typeof date != ‘object‘) || (d.constructor != Date)) // 參數合法性校正        throw Error(arguments[0] + ‘:類型不為Date類型‘);    if (/H+/.test(fmt) && /h+/.test(fmt))        throw Error("小時格式錯誤,同類型只能連續出現一次!");        /* 模板參數校正,正則驗證方法 */    var verify = function(Rex ){        var arr = new RegExp(Rex).exec(fmt); // 獲得匹配結果數組        if (!arr) // 匹配失敗返回            return "";        if (fmt.split(Rex).length > 2)  // 同一類型間隔出現多次            throw Error("fmt格式錯誤:同類型只能連續出現一次!");        return arr[0];    };    /**     * 提供月、天、時、分、秒通用匹配替換     * @param {對象o屬性key} r     * @param {r對應正則對象} rex     **/    var common = function(r, rex) {        if(len !=1 && len !=2)            throw Error("月份格式錯誤:M只能出現1/2次");        len == 2 ? fmt=fmt.replace(rex, o[r].length==1 ? "0"+o[r] : o[r]) : fmt=fmt.replace(rex, o[r]);    }        var o = { // 資料存放區對象        "y+": date.getFullYear() + "", // 年        "q+": Math.floor((date.getMonth() + 3) / 3), // 季度        "M+": date.getMonth() + 1 + "", // 月        "d+": date.getDate() + "", // 日        "H+": date.getHours() + "", // 24時        "h+": date.getHours() + "", // 12時        "m+": date.getMinutes() + "", // 分        "s+": date.getSeconds() + "", // 秒        "S+": date.getMilliseconds() // 毫秒    }            for(var r in o) {        var rex, len, temp;        rex = new RegExp(r);        temp = verify(rex); // 匹配所得字串        len = temp.length; // 長度                if(!len || len == 0)             continue;                    if(r == "y+") {             if(len !=2 && len != 4)                throw Error("年份格式錯誤:y只能出現2/4次");            len == 2 ? fmt=fmt.replace(rex, o[r].substr(2,3)) : fmt=fmt.replace(rex, o[r]);        } else if(r == "q+") {            if(len != 1)                throw Error("季度格式錯誤:q只能出現1次");            fmt=fmt.replace(rex, o[r]);        } else if(r == "h+") {            if(len !=1 && len !=2)                throw Error("小時格式錯誤:h只能出現1/2次");            var h = (o[r] > 12 ? o[r]-12 : o[r]) + "";            len == 2 ? fmt=fmt.replace(rex, h.length==1 ? "0"+h : h) : fmt=fmt.replace(rex, h);        }  else if(r == "S+") {            if(len != 1)                 throw Error("毫秒數格式錯誤:S只能出現1次");            fmt=fmt.replace(rex, o[r]);        }else {    // (r=="M+" || r=="d+" || r=="H+" || r=="m+" || r=="s+")            common(r, rex)        }      }    return fmt;}

上幾個示範效果,供大家參考:

console.log(DateFormat(new Date(),‘yyyy年第q季度M月dd日HH時m分s秒S毫秒‘));

console.log(DateFormat(new Date(),‘yyyy年yy第q季度M月dd日HH時m分s秒S毫秒‘));

console.log(DateFormat(new Date(),‘yyyy年第q季度M月dd日Hh時m分s秒S毫秒‘));

console.log(DateFormat("我不是時間對象",‘yyyy年第q季度M月dd日Hh時m分s秒S毫秒‘));

console.log(DateFormat(new Date(),‘yyyy年第q季度MMM月dd日HH時m分s秒S毫秒‘));

其他效果就不一一列舉了,感興趣的可以把代碼拷貝下來直接測試就行了,有任何BUG或者有待最佳化的地方請慷慨指正哦。

ps:歡迎轉載,轉載請註明出處:http://www.cnblogs.com/liuyitian/p/4136716.html

                          寫作不易,難免有疏漏和錯誤,還請慷慨指正,不錯請推薦

                                      每天多學一點點     代碼少敲一點點 

js時間格式化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.