Javascript 格式化日期的贼直接的解决方案

场景

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

案例:
在这里插入图片描述
欢迎交流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值