场景
咱们都知道,一般咱们格式化时间都会选择类似 moment.js 或者 Intl.formatDateTime 这样的方案。然而,很多时候不想这么干,就想简简单单的实现一下。
每次都去百度找算法,看的我很难受。还是写个简单粗暴的吧:
PS: 优化也很方便,暂时先这么写了。
Date.prototype.format = function (format = 'YYYY-MM-DD HH:mm:ss.sss') {
const fillZero = (n, zeros = '00') => (zeros + n).slice(-(zeros.length))
const year = this.getFullYear()
const month = fillZero(this.getMonth() + 1)
const date = fillZero(this.getDate())
const hour = fillZero(this.getHours())
const min = fillZero(this.getMinutes())
const sec = fillZero(this.getSeconds())
const milisec = fillZero(this.getMilliseconds(), '000')
return format
.replace('YYYY', year)
.replace('MM', month)
.replace('DD', date)
.replace('HH', hour)
.replace('mm', min)
.replace('sss', milisec)
.replace('ss', sec)
}
案例:
欢迎交流。