思路:学习过java的应该都知道,java中有很重要的一个特性,就是封装的特性。
工作和学习中经常遇到js获取当前时间,将时间进行格式化,在这里自己封装了一下,供大家参考。
代码:
Date.prototype.format = function (format) {
var args = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
"S": this.getMilliseconds()
};
if (/(y+)/.test(format))
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var i in args) {
var n = args[i];
if (new RegExp("(" + i + ")").test(format))
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? n : ("00" + n).substr(("" + n).length));
}
return format;
};
支持各种时间格式:
yyyy-mm-dd hh:MM:ss
实例:alert("curDate: " + new Date().format("yyyy-MM-dd hh:mm:ss"));
yyyy-mm-dd
实例:alert("curDate: " + new Date().format("yyyy-MM-dd "));
根据自己的需要,自己定义即可。