Closed2

Intlを使った相対時刻表示

けのびけのび

10 時間前 などの時刻表示を得たい時に、dayjsといったサードパーティライブラリにあるが、 Intl にある RelativeTimeFormat() を使えば、実現はできる。

比較する時刻の差分を算出して、条件でラベルを出し分けする感じ。

// 言語は日本語としている
const formatter = new Intl.RelativeTimeFormat('ja', { numeric: 'auto' })

function getRelativeTimeDifference(targetDate: Date, now = new Date()) {
  const diffInMilliseconds = now.getTime() - targetDate.getTime()

  if (Math.abs(diffInMilliseconds) < 60_000) {
    const diffInSeconds = Math.floor(diffInMilliseconds / 1_000)
    return formatter.format(-diffInSeconds, 'second')
  }
  if (Math.abs(diffInMilliseconds) < 3_600_000) {
    const diffInMinutes = Math.floor(diffInMilliseconds / 60_000)
    return formatter.format(-diffInMinutes, 'minute')
  }
  if (Math.abs(diffInMilliseconds) < 86_400_000) {
    const diffInHours = Math.floor(diffInMilliseconds / 3_600_000)
    return formatter.format(-diffInHours, 'hour')
  }

  const daysDifference = Math.floor(diffInMilliseconds / 86_400_000)
  if (Math.abs(daysDifference) < 30) {
    return formatter.format(-daysDifference, 'day')
  }

  const monthsDifference = Math.floor(daysDifference / 30)
  if (Math.abs(monthsDifference) < 12) {
    return formatter.format(-monthsDifference, 'month')
  }

  const yearsDifference = Math.floor(monthsDifference / 12)
  return formatter.format(-yearsDifference, 'year')
}

あとは要件に合わせて調整して使ってもらえれば。

けのびけのび

相対時刻表示は、年月日時分秒の表示よりも直感的で分かりやすいので、標準機能で実装できるのは嬉しい。

このスクラップは1ヶ月前にクローズされました