js实现日期,刚刚、10秒前、3天前、2个月前...

80 阅读1分钟

实现非纯原生,用到了moment.js

下载方式:

npm:npm install moment --save

yarn:yarn add moment

实现方法:

/** 
 * 根据传入的日期判断
 * 0-10秒显示刚刚
 * 10-60秒显示n秒前
 * 1-60分显示n分钟前
 * 1-60分显示n分钟前
 * 1-24小时显示n小时前
 * 1-30天显示n天前
 * 1-12月显示n月前
 * 1年及以上显示n年前
*/
export const judgeTimeDifference = (time = '2023-06-28 15:56:00') => {
  let yearUnit = moment().diff(moment(time), 'years')
  if (yearUnit > 0) {
    return `${yearUnit}年前`
  }
  let monthUnit = moment().diff(moment(time), 'months')
  if (monthUnit > 0) {
    return `${monthUnit}个月前`
  }
  let dayUnit = moment().diff(moment(time), 'days')
  if (dayUnit > 0) {
    return `${dayUnit}天前`
  }
  let hourUnit = moment().diff(moment(time), 'hours')
  if (hourUnit > 0) {
    return `${hourUnit}小时前`
  }
  let minUnit = moment().diff(moment(time), 'minutes')
  if (minUnit > 0) {
    return `${minUnit}分钟前`
  }
  let secondUnit = moment().diff(moment(time), 'seconds')
  if (secondUnit > 10) {
    return `${secondUnit}秒前`
  } else {
    return '刚刚'
  }
}