Intl.RelativeTimeFormat 但同时包含分钟和秒、小时和分钟、天和小时

jul*_*ien 7 javascript

我想知道如何创建一个函数,该函数需要时间戳并返回相对时间格式,例如显示in 2 hours and 15 minutes, in 2 minutes and 15 seconds, one day and 6 hours ago, 6 hours and 13 minutes ago

必须使用它Intl.RelativeTimeFormat才能自动本地化。

我已经有这个功能,但它只显示一个单位,而不是同时显示两个。

const fromNow = function (timestamp) {
  const now = Date.now();
  const diff = timestamp - now;
  const days = diff / (1000 * 60 * 60 * 24);
  const hours = (diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
  const minutes = (diff % (1000 * 60 * 60)) / (1000 * 60);
  const seconds = (diff % (1000 * 60)) / 1000;
  const relative = new Intl.RelativeTimeFormat();

  if (diff > 0) {
    // If the difference is positive, the timestamp is in the future
    if (days >= 1) {
      return `${relative.format(Math.round(days), "day")}`;
    }
    if (hours >= 1) {
      return relative.format(Math.round(hours), "hour");
    }
    if (minutes >= 1) {
      return relative.format(Math.round(minutes), "minute");
    }
    if (seconds >= 0) {
      return relative.format(Math.round(seconds), "second");
    }
  }
  if (diff < 0) {
    // If the difference is negative, the timestamp is in the past
    if (Math.abs(days) >= 1) {
      return relative.format(Math.round(days), "day");
    }
    if (Math.abs(hours) >= 1) {
      return relative.format(Math.round(hours), "hour");
    }
    if (Math.abs(minutes) >= 1) {
      return relative.format(Math.round(minutes), "minute");
    }
    if (Math.abs(seconds) >= 0) {
      return relative.format(Math.round(seconds), "second");
    }
  }
  return "";
};
export default fromNow;

Run Code Online (Sandbox Code Playgroud)