JS练习_时间Time的格式化

export function formatDate(data,fmt){
  // 1.获取年份
  // y+ 表示,1个多个y
  // y* 表示,0个或多个y
  // y? 表示,0个或者一个y
  // yyyy - 2019 , yy - 19 , y - 9
  if (/(y+)/.test(fmt)){
    // fmt.replace(‘yy’,(2019).截取(4-2)
    fmt = fmt.replace(RegExp.$1,(date.getFullYear() + '').substr(4- RegExp.$1.length));
  }

  // 2.获取
  // M+ -> 正则表达式中的一个规则
  let o = {
    'M+': date.getMonth() +1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (let k in o){
    if (new RegExp(`(${k})`).test(fmt)){
      let str = o[k] + '';
      fmt = fmt.replace(RegExp.$1,(RegExp.$1.length === 1) ? str : padLeftZero(str));
    }
  }
  return fmt;
}

function padLeftZero(str){
  return ('00' + str).substr(str.length);
}
posted @ 2021-12-13 20:31  博客zhu虎康  阅读(58)  评论(0编辑  收藏  举报