js new Date() 格式

一、日期格式化顯示:

對 new Date() 得到日期的進行格式顯示擴展,擴展方法如下:

Date.prototype.Format = function (fmt) { //author: meizz 

         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;

}


使用例子:

       (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") //輸出結果: 2017-01-23 09:36:10.400
       (new Date()).Format("yyyy-M-d h:m:s.S")      //輸出結果: 2017-1-23 9:36:35.572


二、js獲取時間戳

var timestamp1 = (new Date()).valueOf();   //輸出結果:1485136737263
var timestamp2 = (new Date()).getTime();  //輸出結果:1485136744758


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章