Twitter Display Requirements
TwitterのAPIを使ってTweetを表示する場合、Timestampを決まった表記の相対時間で表示することが求められています。
Tweet Timestamps
- 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.
- Tweets older than 24 hours should show a short form date including the day and month, e.g., “6 Jun”.
軽量(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)