您的位置:首页 > Web前端 > JavaScript

JavaScript原形继承方式添加自定义格式化方法

2016-04-29 00:00 579 查看
摘要: 我们以JavaScript原形继承方式添加自定义格式化Date方法

我们通过JS的原形继承方法添加如下格式化Date的方法:

Date.prototype.pattern=function(fmt) {
var o = {
"M+" : this.getMonth()+1, //Month
"d+" : this.getDate(), //Day
"h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //12 hour
"H+" : this.getHours(), //24 hour
"m+" : this.getMinutes(), //Minute
"s+" : this.getSeconds(), //Second
"q+" : Math.floor((this.getMonth()+3)/3), //Quarter
"S"  : this.getMilliseconds(), //Millisecond
't+' : this.getHours() < 12 ? 'am' : 'pm',
'T+' : this.getHours() < 12 ? 'AM' : 'PM'
};
var week = {
"0" : "Sunday",
"1" : "Monday",
"2" : "Tuesday",
"3" : "Wednesday",
"4" : "Thursday",
"5" : "Friday",
"6" : "Saturday"
};
if(/(y+)/.test(fmt)){
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
if(/(E+)/.test(fmt)){
fmt=fmt.replace(RegExp.$1, week[this.getDay()+""]);
}
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)));      &nb
7fe0
sp;
}
}
return fmt;
}


如上所示,调用实例如下:

var date = new Date();
window.alert(date.pattern("hh:mm:ss T MM/dd/yyyy EE"));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息