js date格式化yyyy-MM-dd(转)

Date.prototype.format = function(format)
{
 var o = {
 "M+" : this.getMonth()+1, //month
 "d+" : this.getDate(),    //day
 "h+" : this.getHours(),   //hour
 "m+" : this.getMinutes(), //minute
 "s+" : this.getSeconds(), //second
 "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
 "S" : this.getMilliseconds() //millisecond
 }
 if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
 (this.getFullYear()+"").substr(4 - RegExp.$1.length));
 for(var k in o)if(new RegExp("("+ k +")").test(format))
 format = format.replace(RegExp.$1,
 RegExp.$1.length==1 ? o[k] :
 ("00"+ o[k]).substr((""+ o[k]).length));
 return format;
}

对Date的原型进行了改造,用起来比较方便

var d1 = new Date();
d1.format('yyyy-MM-dd');

var d2 = new Date();
d2.format('yyyy-MM-dd hh:mm:ss');
发布了77 篇原创文章 · 获赞 21 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/f1370335844/article/details/102584217