JavaScript | Intl.RelativeTimeFormat を使って分・時間・月など、さまざまな単位で相対時間を表示する方法

javascrpit JavaScript
スポンサーリンク

では「相対時間と絶対時間を組み合わせて表示する方法(例: ‘3日前 14:30’)」を作ってみましょう。


ゴール

  • SNS風の「◯日前」などの相対表現
  • さらに「何時何分」などの絶対時刻を併記
  • 例: 3日前 14:30 / yesterday 18:47

実装例

function timeAgoWithExact(date, lang = 'ja') {
  const now = new Date();
  const diffMs = now - date;
  const diffSec = Math.floor(diffMs / 1000);

  const rtf = new Intl.RelativeTimeFormat(lang, { numeric: 'auto' });

  // 相対時間の計算
  let relative;
  if (diffSec < 60) {
    relative = rtf.format(-diffSec, 'second');
  } else if (diffSec < 3600) {
    relative = rtf.format(-Math.floor(diffSec / 60), 'minute');
  } else if (diffSec < 86400) {
    relative = rtf.format(-Math.floor(diffSec / 3600), 'hour');
  } else if (diffSec < 172800) {
    relative = lang === 'ja' ? '昨日' : 'yesterday';
  } else if (diffSec < 2592000) {
    relative = rtf.format(-Math.floor(diffSec / 86400), 'day');
  } else if (diffSec < 31536000) {
    relative = rtf.format(-Math.floor(diffSec / 2592000), 'month');
  } else {
    relative = rtf.format(-Math.floor(diffSec / 31536000), 'year');
  }

  // 絶対時間のフォーマット
  const timeFormatter = new Intl.DateTimeFormat(lang === 'ja' ? 'ja-JP' : 'en-US', {
    hour: '2-digit',
    minute: '2-digit'
  });
  const exactTime = timeFormatter.format(date);

  return `${relative} ${exactTime}`;
}

// 実行例
console.log(timeAgoWithExact(new Date(Date.now() - 3 * 24 * 60 * 60 * 1000), 'ja'));
// "3日前 18:54" など

console.log(timeAgoWithExact(new Date(Date.now() - 26 * 60 * 60 * 1000), 'en'));
// "yesterday 18:54"
JavaScript

ポイント

  • 相対時間Intl.RelativeTimeFormat
  • 絶対時間Intl.DateTimeFormat
  • 両方を組み合わせることで「いつ頃か」と「正確な時刻」を同時に伝えられる

💡 これで「SNS風の相対時間 + 正確な時刻」表示が完成しました。
実務ではニュース記事やSNS投稿のタイムスタンプにとても便利です。

タイトルとURLをコピーしました