js 格式化时间戳函数

方法一:使用Moment.js插件 https://momentjs.com/
方法二:自己写函数:
function formatDate(timestamp, fmt) {
  let time = new Date(timestamp)
  if (/(Y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  var t = {
    'M+': time.getMonth() + 1,
    'D+': time.getDate(),
    'h+': time.getHours(),
    'm+': time.getMinutes(),
    's+': time.getSeconds()
  }
  for (var i in t) {
    if (new RegExp(`(${i})`).test(fmt)) {
      let str = t[i] + ''
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : addZero(str))
    }
  }
  return fmt
}

function addZero(str) {
  return ('00' + str).substr(str.length)
}

调用函数:

let formatTime = formatDate(time, 'YYYY-MM-DD hh:mm')

你可能感兴趣的:(js 格式化时间戳函数)