interface Date {
format: (this: Date, fmt: string) => string
}
Date.prototype.format = function (fmt) {
const ss = new Map([
[/(M+)/, this.getMonth() + 1],
[/(d+)/, this.getDate()],
[/(H+)/, this.getHours()],
[/(h+)/, this.getHours() % 12],
[/(m+)/, this.getMinutes()],
[/(s+)/, this.getSeconds()],
[/(q+)/, Math.floor((this.getMonth() + 3) / 3)],
[/(S)/, this.getMilliseconds()],
]);
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, this.getFullYear().toString().substr(4 - RegExp.$1.length));
}
ss.forEach((val, key) => {
if (key.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (1 == RegExp.$1.length) ? val.toString() : ((`00${val}`).substr(val.toString().length)));
}
});
return fmt;
}
console.info(new Date().format("yyyy-MM-dd HH:mm:ss"));
console.info(new Date().format("yyyy/MM/dd hh:mm:ss"));
console.info(new Date().format("yyyy年MM月dd日 第q季度"));
console.info(new Date().format("yyyyMMddHHmmss-S"));
(() => {
const format2 = s => (`00${s}`).substr(s.length);
Date.prototype.toCommonString = function () {
const d = this;
const format2 = s => (`00${s}`).substr(s.length);
const yyyy = d.getFullYear().toString();
const MM = format2((d.getMonth() + 1).toString());
const dd = format2(d.getDate().toString());
const HH = format2(d.getHours().toString());
const mm = format2(d.getMinutes().toString());
const ss = format2(d.getSeconds().toString());
return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}`;
};
Date.prototype.toIDString = function () {
const d = this;
const yyyy = d.getFullYear().toString();
const MM = format2((d.getMonth() + 1).toString());
const dd = format2(d.getDate().toString());
const HH = format2(d.getHours().toString());
const mm = format2(d.getMinutes().toString());
const ss = format2(d.getSeconds().toString());
return `${yyyy}${MM}${dd}${HH}${mm}${ss}`;
};
})();
console.log(new Date().toCommonString());
console.log(new Date().toIDString());