likes
comments
collection
share

js formatDate RegExp.$1 非标准化 使用RegExp.exec代替

作者站长头像
站长
· 阅读数 32
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) {
        if (/(y+)/.test(k)) {
          fmt = fmt.replace(ret[1], opt[k].substring(4 - ret[1].length))
        } else {
          fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
        }
      }
    }
    return fmt
  }
}