时间戳转化“刚刚”、“几小时前”、“几天前”、“几周前”等形式的js代码片段

发布时间 2023-06-03 14:50:40作者: 木人子韦一日尘

代码片段(可用于vue过滤器)

function getTimeStr(timestamp) {
  const now = new Date();
  const date = new Date(timestamp);
  const diff = (now - date) / 1000; // 毫秒转换为秒

  if (diff < 60) {
    return "刚刚";
  } else if (diff < 3600) {
    return Math.floor(diff / 60) + "分钟前";
  } else if (diff < 86400) {
    return Math.floor(diff / 3600) + "小时前";
  } else if (diff < 604800) {
    return Math.floor(diff / 86400) + "天前";
  } else {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
  }
}


使用方式

const timestamp = 1622198234000; // 假设这是一个时间戳,单位毫秒
const timeStr = getTimeStr(timestamp); // 将时间戳转换为刚刚、几小时前、几天前、几周前、具体日期的字符串
console.log(timeStr); // 输出结果可能为:5天前 或者 2021-05-28(具体日期根据传入的时间戳而定)