LoginSignup
5
3

More than 5 years have passed since last update.

Twitterの相対時間を`twitter.relative.time.js`を使って実現する

Posted at

Twitter Display Requirements

TwitterのAPIを使ってTweetを表示する場合、Timestampを決まった表記の相対時間で表示することが求められています。

Tweet Timestamps

  1. For Tweets that have been sent in the last 24 hours, use the short form timestamp relative to the current time, for example “20s” for a Tweet sent 20 seconds ago, “3m” for 3 minutes ago, “5h” for 5 hours ago.
  2. Tweets older than 24 hours should show a short form date including the day and month, e.g., “6 Jun”.

Display Requirements | Twitter Developers

軽量(8kb)で依存ライブラリのないtwitter.relative.time.jsを使えば簡単にこれを実現することができます。

dforest/twitter-relative-time-js

使い方

twitter.relative.time.min.jsをダウンロードして読み込んでください。

そして相対時間にしたいDateオブジェクトに対して.toTwitterRelativeTime()するだけでDisplay Requirementsに準拠した相対時間になります。

new Date().toTwitterRelativeTime()
//=> 7s (for 7 seconds ago)
//=> 13m (for 13 minutes ago)
//=> 19h (for 19 hours ago)
//=> 23 Jan (older than 24 hours)

15ヶ国語対応

また、相対時間の表記として、以下の16ヶ国語にも対応しています。

  • 英語 en
  • 日本語 ja
  • アラビア語 ar
  • ドイツ語 de
  • スペイン語 es
  • フランス語 fr
  • ヒンディー語 hi
  • インドネシア語 id
  • イタリア語 it
  • 韓国語 ko
  • マレー語 ms
  • ポルトガル語 pt
  • ロシア語 ru
  • トルコ語 tr
  • 簡体中国語 zh-CN
  • 繁体中国語 zh-TW
new Date().toTwitterRelativeTime('ja')
//=> 7秒前 (for 7 seconds ago)
//=> 13分前 (for 13 minutes ago)
//=> 19時間前 (for 19 hours ago)
//=> 1月23日 (older than 24 hours)

dforest/twitter-relative-time-js

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3