格式化时间为指定类型

171 阅读1分钟

格式化时间工具文件

/**
 * 解析时间为指定格式的字符串
 * @param {(Object|string|number)} date 待格式化的时间
 * @param {string} fmt 时间格式, 默认值是'yyyy-MM-dd HH:mm:ss'
 * @returns {string} 格式成功或者失败的结果
 */
export function dateFormat(date, fmt = 'yyyy-MM-dd HH:mm:ss') {
  if (arguments.length === 0) {
    return ''
  }

  if (typeof date === 'string') {
    date = new Date(date.replace(/-/gi, '/'))
  }

  if (typeof date === 'number') {
    if (('' + date).length < 13) {
      date.padEnd(19, '0')
    }
    date = new Date(date)
  }
  const dateObj = {
    y: date.getFullYear(), // 年份,注意必须用getFullYear
    M: date.getMonth() + 1, // 月份,注意是从0-11
    d: date.getDate(), // 日期
    q: Math.floor((date.getMonth() + 3) / 3), // 季度
    w: date.getDay(), // 星期,注意是0-6
    H: date.getHours(), // 24小时制
    h: date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, // 12小时制
    m: date.getMinutes(), // 分钟
    s: date.getSeconds(), // 秒
    S: date.getMilliseconds() // 毫秒
  }

  const week = ['天', '一', '二', '三', '四', '五', '六']
  const dateObjKeys = ['y', 'M', 'd', 'q', 'w', 'H', 'h', 'm', 's', 'S']

  for (let i = 0; i < dateObjKeys.length; i++) {
    let key = dateObjKeys[i]

    fmt = fmt.replace(new RegExp(`${key}+`, 'g'), match => {
      let dateValStr = dateObj[key] + ''

      if (key === 'w') {
        return (match.length > 2 ? '星期' : '周') + week[dateValStr]
      }
      dateValStr = dateValStr.padStart(match.length, '0')
      return dateValStr
    })
  }
  return fmt
}

使用示例

在HTML中使用

  <script type="module">
    // 导入
    import {dateFormat} from './index.js'
    let time = new Date('2020/03/16 08:20:50')
    // 格式化
    const timeStr = dateFormat(time, 'yyyy-MM-d HH:mm:s')
    console.log(timeStr)
  </script>