封装两个日期时间处理函数

158 阅读2分钟

格式化日期函数

function parseTime(time, cFormat) {
  // ! arguments时伪数组,收集所有实参,箭头函数不可使用
  // ! ||后面是为了防止传递进去undefined和null
  if (arguments.length === 0 || !time) {
    return null
  }

  // ! 格式化目标格式,如果没传,默认是后面的 '{y}-{m}-{d} {h}:{i}:{s}' 格式
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

结果输出

console.log(parseTime(new Date())) // 不传递参数,默认是这种2023-01-02 17:31:17
console.log(parseTime(new Date(), '{y}-{m}-{d}')) //2023-01-02

计算时间差函数

function formatTime(time, option) {
  // 类型转换,转成字符串
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

输出结果

// 第一个参数要传递进去一个时间戳
console.log(formatTime(new Date(),'2023-01-02 17:31:17'))// 刚刚

console.log(formatTime(new Date('2023-01-01 17:31:17'),'2023-01-02 17:31:17'))// 1天前

console.log(Date.now())// 输出当前系统时间的时间戳 1672652753408
console.log(Date.now())// 输出当前系统时间的时间戳 1672652753409
// 上面两个时间是又差距的,因为系统计算也是要时间的