Drcus | 王亚振

Drcus | 王亚振

随便写,记录点东西

JS 显示多少月、多少分钟之前

发布于:  

函数名为 dateDiff,接受一个参数必须参数 timestamp

函数会判断是否满足13位时间戳,如果不满足则自动补全。

完整代码如下:

const dateDiff = function(timestamp) {
  // 判断补全
  let arrTime = (timestamp + '').split('')
  for (let start = 0; start < 13; start++) {
      if (!arrTime[start] ) {
        arrTime[start] = '0'
      }
  }
  timestamp = arrTime.join('') * 1
  
  let minute = 1000 * 60
  let hour = minute * 60
  let day = hour * 24
  let week = day * 7
  let month = day * 30
  let now = Date.now()
  let diffValue = now - timestamp
  
  // 本地时间小于变量时间
  if (diffValue < 0) {
    return '不久前'
  }
  
  // 时间差异量级
  let monthC = diffValue / month
  let weekC = diffValue / week
  let dayC = diffValue / day
  let hourC = diffValue / hour
  let minC = diffValue / minute
  
  // 补零
  const zero = value => value < 10 ? '0' + value : value
  
  if (monthC > 12) {
    // 超过一年
    return (function() {
      const d = new Date(timestamp)
      return `${d.getFullYear()}${zero(d.getMonth()+1)}${zero(d.getDay())}日`
    })()
  } else if (monthC >= 1) {
    return `${parseInt(monthC)}月前`
  } else if (weekC >= 1) {
    return `${parseInt(weekC)}周前`
  } else if (dayC >= 1) {
    return `${parseInt(dayC)}日前`
  } else if (hourC >= 1) {
    return `${parseInt(hourC)}小时前`
  } else if (minC >= 1) {
    return `${parseInt(minC)}分钟前`
  }
  return '刚刚'
}

~^_^~ 一片小花园 ?

赏赐