实现一个日期格式化方法(可自定义模版)

193 阅读1分钟

自定义模板原理:把外部传入的模板用replace方法根据正则直接匹配替换,然后返回替换完的模板就是格式化好的一个日期。包含年月日时分秒,以及星期。

不废话直接上代码

    /**
     * 格式化日期
     * @param {temp} 'YYYY-MM-DD hh:mm:ss'
     * @example {1} new Date().formatDate('yyy-MM-dd HH:mm:ss 周w') ==> "021-12-03 17:48:34 周五"
     * @example {2} new Date().formatDate('YYYY-MM-DD hh:mm:ss 周w') ==> "2021-12-03 17:49:20 周五"
     */
    Date.prototype.formatDate = function(temp='YYYY-MM-DD hh:mm:ss'){
      let date = this ? new Date(this) : new Date();
      function padZero(num){  // 加零
        return (num+'').padStart(2, 0)
      }
      const dateObj = {
            'M+': date.getMonth()+1,
            'D+|d+': date.getDate(),
            'H+|h+': date.getHours(),
            'm+': date.getMinutes(),
            's+': date.getSeconds()
          },
          week = ['日', '一', '二', '三', '四', '五', '六'];
      if(/(Y+|y+)/.test(temp)){ // 处理年:包含4个占位符
        temp = temp.replace(RegExp.$1, (date.getFullYear()+'').substr(4-RegExp.$1.length))
      }
      if(/(W+|w+)/.test(temp)){ // 处理星期
        temp = temp.replace(RegExp.$1, week[date.getDay()])
      }
      let tempNum = '';
      for(let key in dateObj){
        if(new RegExp(`(${key})`).test(temp)){
          tempNum = dateObj[key]
          temp = temp.replace(RegExp.$1, (RegExp.$1.length === 1) ? tempNum : padZero(tempNum))
        }
      }
      return temp
    }