将时间戳或日期对象转化成常用格式的js方法

276 阅读1分钟

/**
 * 时间日期格式化方法
 * @param {number|Date} time 时间戳或日期对象
 * @param {string} fmt 格式
 * @returns string
 */
function formatTime(time, fmt) {
  let date = new Date(time)
  const o = {
    'y+': date.getFullYear(),
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for(var key in o) {
    if (fmt.match(new RegExp(`(${key})`))){
      // 当遇到0-9范围段的数字时根据fmt具体要求补0
      let replaceStr = RegExp.$1.length < 2 ? o[key] : o[key].toString().length < 2 ? '0' + o[key] : o[key]
      fmt = fmt.replace(RegExp.$1, replaceStr)
    }
  }
  return fmt
}

let currentTimestamp = Date.now()
console.log(formatTime(currentTimestamp, 'yyyy-MM-dd hh:mm:ss'))

let date = new Date()
console.log(formatTime(date, 'yyyy-MM-dd hh:mm:ss'))