JS时间戳timestamp格式化为指定格式

249 阅读1分钟

可将10位,13位的时间戳格式化为指定时间格式


export const formatTime = (timestamp, type) => {
  if (!timestamp) return ''
  
  let realType = type ? type : 'YYYY-MM-DD'
  let realTime = ''
  let date = new Date(timestamp.length === 10 ? timestamp * 1000 : timestamp * 1)
  if (date == 'Invalid Date'return '非法日期'
  
  let Y = date.getFullYear(),
    M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1,
    D = date.getDate(),
    h = date.getHours(),
    m = date.getMinutes(),
    s = date.getSeconds()

  switch (realType) {
    case 'YYYY-MM-DD':
      realTime = `${Y}-${M}-${D}`
      break
    case 'YYYY/MM/DD':
      realTime = `${Y}/${M}/${D}`
      break
    case 'YYYY-MM-DD HH:mm:ss':
      realTime = `${Y}-${M}-${D} ${h}:${m}:${s}`
      break
    case 'YYYY/MM/DD HH:mm:ss':
      realTime = `${Y}/${M}/${D} ${h}:${m}:${s}`
      break
    default:
      break
  }

  return realTime
}