javascript Date format(js日期格式化)
1 Date.prototype.format = function (format) { 2 if (!format) { 3 format = "yyyy-MM-dd hh:mm:ss"; 4 } //如果不是这个格式强制转换 5 var o = { 6 "M+": this.getMonth() + 1, 7 "d+": this.getDate(), 8 "h+": this.getHours(), 9 "m+": this.getMinutes(), 10 "s+": this.getSeconds(), 11 "q+": Math.floor((this.getMonth() + 3) / 3), 12 "S": this.getMilliseconds() 13 14 }; 15 if (/(y+)/.test(format)) { 16 format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); 17 } 18 for (var k in o) { 19 if (new RegExp("(" + k + ")").test(format)) { 20 format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); 21 } 22 } 23 return format; 24 };
调用方法:
var time1 = new Date().format("yyyy-MM-dd HH:mm:ss"); var time2 = new Date().format("yyyy-MM-dd");