DateFormat 时间格式匹配,自动补零

/**
 * 时间格式函数
 *
 * @export
 * @param {any} [date=new Date()]
 * @param {string} [format='YYYY-MM-DD']
 * @returns
 * 
 *  可传参数 
 *  2021/10/1 10:00:00 (string类型)
 *  2021.10.1 10:00:00 (string类型)
 * 	2021-10-1 10:00:00 (string类型)
 *  时间戳9位或13位(number类型)
 *  不传参数默认当前时间
 */
 
export function DateFormat (date = new Date(), format = 'YYYY-MM-DD') {
  let time = ''
  if (!date) return ''
  if (!(date instanceof Date)) {
    const reg = new RegExp(/^[1-9]\d{9}$/g).test(date + '')
    const reg1 = new RegExp(/^[1-9]\d{12}$/g).test(date + '')
    const reg2 = new RegExp(/^[1-9]\d{3}[-/\.]\d{1,2}[-/\.]\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}$/g).test(date)
    if (reg) {
      time = new Date(parseInt(date) * 1000)
    } else if (reg1) {
      time = new Date(parseInt(date))
    } else if (reg2) {
      time = new Date(date)
    } else {
      return ''
    }
  } else {
    time = date
  }
  const year = time.getFullYear()
  const month = time.getMonth() + 1
  const day = time.getDate()
  const hour = time.getHours()
  const min = time.getMinutes()
  const sec = time.getSeconds()

  return format
    .replace('YYYY', year)
    .replace('MM', +month >= 10 ? month : `0${month}`)
    .replace('DD', +day >= 10 ? day : `0${day}`)
    .replace('HH', +hour >= 10 ? hour : `0${hour}`)
    .replace('mm', +min >= 10 ? min : `0${min}`)
    .replace('ss', +sec >= 10 ? sec : `0${sec}`)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值