use-relative-timestamp.tsx

a react hook for formatting timestamps relative to now

function useRelativeTimestamp(ts: number) {
  const now = Date.now();
  let displayTime = "";

  const diff = now - ts;
  const timestamp = new Date(ts);

  if (diff <= 1000 * 60 * 60) {
    const formatter = new Intl.RelativeTimeFormat("en", { numeric: "auto" });

    const diffInSecs = Math.round(diff / 1000);
    if (diffInSecs < 60) {
      displayTime = formatter.format(-diffInSecs, "seconds");
    } else {
      const diffInMinutes = Math.round(diffInSecs / 60);
      displayTime = formatter.format(-diffInMinutes, "minutes");
    }
  } else if (diff <= 1000 * 60 * 60 * 24) {
    displayTime = timestamp.toLocaleTimeString([], {
      hour: "numeric",
      minute: "numeric",
    });
  } else if (diff <= 1000 * 60 * 60 * 24 * 1) {
    displayTime = timestamp.toLocaleTimeString([], {
      hour: "numeric",
      minute: "numeric",
      weekday: "short",
    });
  } else if (diff <= 1000 * 60 * 60 * 24 * 2) {
    displayTime = `Yesterday, ${timestamp.toLocaleTimeString([], {
      hour: "numeric",
      minute: "numeric",
    })}`;
  } else {
    displayTime = timestamp.toLocaleDateString([], {
      hour: "numeric",
      minute: "numeric",
      month: "short",
      day: "numeric",
    });
  }

  return displayTime;
}