6.(JavaScript)获取某个时间与现在的时间差

/**
 * 根据传入的时间与现在的时间差
 * 将时间差转成可读字符串 如:刚刚、3秒前、一小时前等等
 *
 * @param time 需要进行比较的毫秒级时间(毫秒 同时需要 小于 当前时间)
 * @return 返回可读字符串, 大于20天的 将会直接显示日期
 */
export function timeDifference(time) {
  if (time === null || time === undefined) {
    return ''
  }

  // 获取两个日期之间相差的毫秒数
  const timeDifference = Math.abs(Date.now() - time)

  const days = timeDifference / 1000 / 60 / 60 / 24
  const hours = timeDifference / 1000 / 60 / 60 - (24 * Math.floor(days))
  const minutes = timeDifference / 1000 / 60 - (24 * 60 * Math.floor(days)) - (60 * Math.floor(hours))
  const seconds = timeDifference / 1000 - (24 * 60 * 60 * Math.floor(days)) - (60 * 60 * Math.floor(hours)) - (60 * Math.floor(minutes))

  // 1分钟以内(1分钟 = 60000ms)
  if (timeDifference < 60000) {
    // 如果是5秒内
    const just = 5
    if (timeDifference < 1000 * just) {
      return '刚刚'
    } else {
      return Math.floor(seconds) + '秒前'
    }
  }

  // 一小时内(大于 1分钟[60000ms] 小于 1小时[3600000ms])
  if (timeDifference >= 60000 && timeDifference < 3600000) {
    return Math.floor(minutes) + '分钟前'
  }

  // 一天内
  if (timeDifference >= 3600000 && timeDifference < 86400000) {
    return Math.floor(hours) + '小时前'
  }

  // 二十天内
  const twentyDays = 86400000 * 20
  if (timeDifference >= 86400000 && timeDifference < twentyDays) {
    return Math.floor(days) + '天前'
  }

  return ''
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值