js自定义格式化时间戳的格式

题目为 : 写一个模块,外部调用这个模块,请求参数是时间戳,模块要求
今天的时间,统一用24小时写作 03:00、15:04
昨天的时间,统一写昨天
昨天之前的时间,但在本周之内的时间,统一用周一、周二、周三这样来写
上周的时间,统一协作15/3/4,依次是年/月/日
注意当月和日是个位数的时候,不需要用0站位变成两位,其他显示null

function formatTime(time) {
  const __time = new Date(time * 1000)
  function zeroize(num) {
    return (String(num).length == 1 ? '0' : '') + num
  }

  function formatTime1() { //转化成时分秒
    return `${zeroize(__time.getHours())}:${zeroize(__time.getMinutes())}:${zeroize(__time.getSeconds())}`
  }

  function formatTime2() { //转化成年月日
    return `${__time.getFullYear().toString().substr(2,4)}/${__time.getMonth()+1}/${__time.getDate()}`
  }

  function getWeek() {
    const _day = new Date(time * 1000).getDay()
    switch (_day) {
      case 0:
        return '日'
      case 1:
        return '一'
      case 2:
        return '二'
      case 3:
        return '三'
      case 4:
        return '四'
      case 5:
        return '五'
      case 6:
        return '六'
    }
  }
  var now = `${new Date().getFullYear()}/${new Date().getMonth()+1}/${new Date().getDate()} 00:00:00`
  var _now = new Date(now).getTime()
    //时间戳比今天0点小一天就是昨天
  if (time * 1000 < _now && time * 1000 > _now - 24 * 60 * 60 * 1000) {
    return `昨天${formatTime1()}`
  }
  //时间戳大于今天0点就是今天
  if (time * 1000 > _now) {
    return `今天${formatTime1()}`
  }
  //时间戳小于昨天的0点大于本周一的时间戳是本周
  if (time * 1000 < _now - 24 * 60 * 60 * 1000 && time * 1000 > _now - 24 * 60 * 60 * 1000 * (new Date().getDay() - 1)) {
    return `周${getWeek()}`
  }
  //时间戳小于本周一的时间戳大于上周一的时间戳是上周
  if (time * 1000 < _now - 24 * 60 * 60 * 1000 * (new Date().getDay() - 1) && time * 1000 > _now - 24 * 60 * 60 * 1000 * new Date().getDay() - 6 * 24 * 60 * 60 * 1000) {
    return formatTime2()
  }
  return 'null'
}
原文地址:https://www.cnblogs.com/yangwang12345/p/8488204.html