场景
咱们都知道,一般咱们格式化时间都会选择类似 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)
}
案例:

欢迎交流。
本文介绍了一种直接在JavaScript中扩展Date原型的方法来格式化日期时间,避免了使用第三方库如moment.js等,通过简单的代码实现了日期时间的格式化。

564

被折叠的 条评论
为什么被折叠?



