format date to string in format of “5m, 2h, 6d ago” in javascript

index.tsx
function getTimeAgo(timestamp) {
  const seconds = Math.floor((new Date() - timestamp) / 1000);
  let interval = Math.floor(seconds / 31536000);

  if (interval >= 1) {
    return `${interval}y ago`;
  }
  interval = Math.floor(seconds / 2592000);
  if (interval >= 1) {
    return `${interval}m ago`;
  }
  interval = Math.floor(seconds / 86400);
  if (interval >= 1) {
    return `${interval}d ago`;
  }
  interval = Math.floor(seconds / 3600);
  if (interval >= 1) {
    return `${interval}h ago`;
  }
  interval = Math.floor(seconds / 60);
  if (interval >= 1) {
    return `${interval}m ago`;
  }
  return `${Math.floor(seconds)}s ago`;
}
644 chars
26 lines

This getTimeAgo function takes a timestamp as input and returns a formatted string describing the time elapsed since the timestamp. The output format is "Xy ago" for years, "Xm ago" for months, "Xd ago" for days, "Xh ago" for hours, "Xm ago" for minutes, and "Xs ago" for seconds.

gistlibby LogSnag