javascript時間日期格式化程式碼分析

antzone發表於2017-03-21

通常情況下獲取的系統時間總要進行一下格式化處理,下面就是一段能夠對獲取的時間日期格式化的簡單程式碼,能夠滿足簡單的格式化需求,下面就分析一下能夠實現此功能的程式碼,希望能夠給期望瞭解實現原理的朋友帶來一定的幫助。

程式碼如下:

[JavaScript] 純文字檢視 複製程式碼
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+)/.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; 
}  
var odate=new Date().format("yyyy-MM-dd hh:mm:ss"); 
console.log(odate);

相關文章