Date.prototype.format = function (fmt) { var cur = this, result = "", pattern = { "(q+)": Math.ceil((cur.getMonth() + 1) / 3), "(M+)": cur.getMonth() + 1, "(d+)": cur.getDate(), "(h+)": cur.getHours(), "(m+|mi)": cur.getMinutes(), "(s+)": cur.getSeconds(), "(ms)": cur.getMilliseconds() }, yearPattern = /(y+)/, item = {}; yearPattern.test(fmt) && (function () { fmt = fmt.replace(RegExp.$1, cur.getFullYear().toString().substr(4 - RegExp.$1.length)); })(); for (var idx in pattern) { item = new RegExp(idx); item.test(fmt) && (function () { fmt = fmt.replace(RegExp.$1, (1 == RegExp.$1.length ? pattern[idx] : "00{0}".format(pattern[idx]).substr("{0}".format(pattern[idx]).length))); })(); } return fmt; }
调用:
new Date().format("yyyy年MM月dd");