js格式化时间日期代码实例:
时间日期在默认状态下往往不够规整,会影响整体的美观度,所以通常情况下要对时间日期进行格式化,下面就分享一段这样的代码实例,希望能够给需要的朋友带来一定的帮助。
代码实例如下:
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; }; var dt=new Date(); var nowDate=dt.format("yyyy-MM-dd hh:mm:ss"); console.log(nowDate)
以上代码实现了我们的要求,可以返回指定格式的时间日期,指定日期格式的字符串并不是仅仅例子中的一种,而是可以是多,基本可以满足大多数的格式化需求,最好对代码有所理解,这样使用起来更加便利。
原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=10858
更多内容可以参阅:http://www.softwhy.com/javascript/