以下是JS函数,它接受一个时间戳作为输入,并返回距离当前时间的时间差。

function getTimeAgo(timestamp) {
  const now = new Date().getTime();
  const diff = now - timestamp;
  const minute = 60 * 1000;
  const hour = minute * 60;
  const day = hour * 24;
  const week = day * 7;
  const month = day * 30;
  const year = day * 365;

  if (diff < minute) {
    return '刚刚';
  } else if (diff < hour) {
    return Math.floor(diff / minute) + '分钟前';
  } else if (diff < day) {
    return Math.floor(diff / hour) + '小时前';
  } else if (diff < week) {
    return Math.floor(diff / day) + '天前';
  } else if (diff < month) {
    return Math.floor(diff / week) + '周前';
  } else if (diff < year) {
    return Math.floor(diff / month) + '个月前';
  } else {
    return Math.floor(diff / year) + '年前';
  }
}

要使用它,只需调用 getTimeAgo() 函数并传递一个时间戳作为参数。例如:

const timestamp = 1619577977000; // 假设这是一个时间戳
const timeAgo = getTimeAgo(timestamp);
console.log(timeAgo); // 输出:“1天前”
用js写一个时间戳返回距离今天多少时间的函数

原文地址: https://www.cveoy.top/t/topic/gSq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录