javascript扩展date对象格式化日期时间输出(二)


Date.prototype.format=function(format){

//大写字母代表带前导0  

var o={

    'Y':this.getFullYear(),
    'm':this.getMonth()+1,
    'd':this.getDate(),
    'h':this.getHours(),
    'i':this.getMinutes(),
    's':this.getSeconds(),
    'M':this.getMonth2(),
    'D':this.getDate2(),
    'H':this.getHours2(),
    'I':this.getMinutes2(),
    'S':this.getSeconds2()
  
  }
  
  for(var k in o){
    if(new RegExp('('+k+')').test(format)){
        format=format.replace(RegExp.$1,o[k]);
    }
  }
return format;




};


Date.prototype.getMonth2=function(){
  return (this.getMonth()+1)<10?"0"+(this.getMonth()+1):(this.getMonth()+1);
}


Date.prototype.getDate2=function(){
  return (this.getDate())<10?"0"+(this.getDate()):(this.getDate());
}


Date.prototype.getHours2=function(){
  return (this.getHours())<10?"0"+(this.getHours()):(this.getHours());
}


Date.prototype.getMinutes2=function(){
  return (this.getMinutes())<10?"0"+(this.getMinutes()):(this.getMinutes());
}


Date.prototype.getSeconds2=function(){
  return (this.getSeconds())<10?"0"+(this.getSeconds()):(this.getSeconds());
}

eg:

1、alert(new Date().format('Y M D H I S'));

2、alert(new Date().format('Y m d h i s'));

你可能感兴趣的:(javascript)