js 格式化时间

/**
 * 获取年月日 时分秒
 * @param {string | number} time 时间字符串 | 时间戳
 * @returns { year, month, date, hours, minutes, seconds }
 */
function getDate (time) {
  const date = new Date(time)
  const y = date.getFullYear()
  const M = date.getMonth() + 1
  const MM = M > 9 ? M : '0' + M
  const d = date.getDate()
  const dd = d > 9 ? d : '0' + d
  const H = date.getHours()
  const HH = H > 9 ? H : '0' + H
  const m = date.getMinutes()
  const mm = m > 9 ? m : '0' + m
  const s = date.getSeconds()
  const ss = s > 9 ? s : '0' + s

  const t = date.toLocaleTimeString()
  const t_1 = t.substr(0, 2)
  const t_2 = t.slice(2)
  const h = t_2.split(':')[0]
  const hh = h > 9 ? h : '0' + h
  const a_p = t_1 === '上午' ? 'am' : 'pm'

  return { y, M, MM, d, dd, H, HH, m, mm, s, ss, h, hh, a_p }
}

/**
 * 格式化时间类型
 * @param {string | number} time 时间字符串 | 时间戳
 * @param {string} type 时间格式
 * @returns 格式化后时间字符串
 */
function format (time, type) {
  if(time !== null && !time)
    throw('format error: params 1 time is required')
  if(new Date(time) == 'Invalid Date')
    throw('time error: params 1 time is Invalid Date')
  if(type && typeof type !== 'string')
    throw('format error: params 2 type not is a string')

  const { y, M, MM, d, dd, H, HH, m, mm, s, ss, h, hh, a_p } = getDate(time)

  switch(type) {
    case 'yyyy-MM-dd':
      return [y, MM, dd].join('-')
    case 'yyyy-M-d':
      return [y, M, d].join('-')
    case 'HH:mm:ss':
      return [HH, mm, ss].join(':')
    case 'H:m:s':
      return [H, m, s].join(':')
    case 'h:m:s':
      return [h, m, s].join(':') + ' ' + a_p
    case 'yyyy-MM-dd HH:mm:ss':
      return [y, MM, dd].join('-') + ' ' + [HH, mm, ss].join(':')
    case 'yyyy-M-d H:m:s':
      return [y, M, d].join('-') + ' ' + [H, m, s].join(':')
    default:
      return [y, MM, dd].join('-')
  }
}

使用

console.log(format(new Date()))                             // 2021-06-09
console.log(format(null))                                   // 1970-01-01
console.log(format(new Date(), 'yyyy-M-d'))                 // 2021-6-9
console.log(format(new Date(), 'HH:mm:ss'))                 // 10:17:46
console.log(format(new Date(), 'h:m:s'))                    // 10:17:46 am
console.log(format(new Date(), 'yyyy-MM-dd HH:mm:ss'))      // 2021-06-09 10:17:46
console.log(format(new Date(), 'yyyy-M-d h:m:s'))           // 2021-06-09
console.log(format(undefined))                              // Uncaught format error: params 1 time is required
console.log(format(new Date(), 22))                         // Uncaught format error: params 2 type not is a string
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值