JS格式化字符串输出,format(“yyyy年MM月dd hh:mm:ss”)

07. November 2016 HTML5 0

<script type=”text/javascript”>
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+)/i.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;
}//把以上代码复制到JS文件中,即可使用下面的函数格式化时间输出。
function timeshow(){
var time=new Date().format(“yyyy年MM月dd hh:mm:ss”);
$(‘#timeshow’).html(“今天是:”+time);
setTimeout(timeshow,1000);//在指定div输出时钟,每秒更新一次。
}

</script>


Leave a Reply

Your email address will not be published. Required fields are marked *