export default class FormatDate { formatDate (date: Date, fmt: string): string { const o: {[key:string]: string} = { 'M+': date.getMonth() + 1 + '', // 月份 'd+': date.getDate() + '', // 日 'h+': date.getHours() + '', // 小时 'm+': date.getMinutes() + '', // 分 's+': date.getSeconds() + '', // 秒 S: date.getMilliseconds() + '' // 毫秒 } if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) } for (const k in o) { if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) } } return fmt }}
替换为
export default class FormatDate { formatDate (date: Date, fmt: string): string { const opt: {[key: string]: string} = { 'y+': date.getFullYear().toString(), // 年 'M+': (date.getMonth() + 1).toString(), // 月 'd+': date.getDate().toString(), // 日 'h+': date.getHours().toString(), // 时 'm+': date.getMinutes().toString(), // 分 's+': date.getSeconds().toString() // 秒 } for (const k in opt) { const ret = new RegExp('(' + k + ')').exec(fmt) if (ret) { fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k] as string) : (opt[k].padStart(ret[1].length, '0'))) } } return fmt }}