このJavaScriptコードは、Twitter APIのSearch.JSON応答の
プロパティを使用して、ツイートが作成されてから経過した時間を計算します。 Twitterウィジェットまたは同様のアプリケーションに「時間」を表示するのに役立ち、created_at
。
setInterval
関数:calculateSince
この関数は、
created_at
/** * Calculates the time elapsed since a tweet was created. * @param {string} datetime - The 'created_at' datetime string from the Twitter API. * @return {string} - A human-readable string showing the time elapsed. */ function calculateSince(datetime) { const tweetTime = new Date(datetime); const currentTime = new Date(); const minutesElapsed = Math.round((currentTime - tweetTime) / 60000); if (minutesElapsed === 0) { const secondsElapsed = Math.round((currentTime - tweetTime) / 1000); if (secondsElapsed < 10) return 'less than 10 seconds ago'; if (secondsElapsed < 20) return 'less than 20 seconds ago'; return 'half a minute ago'; } else if (minutesElapsed === 1) { return '1 minute ago'; } else if (minutesElapsed < 45) { return minutesElapsed + ' minutes ago'; } else if (minutesElapsed < 1440) { // Less than a day const hoursElapsed = Math.round(minutesElapsed / 60); return 'about ' + hoursElapsed + ' hours ago'; } else if (minutesElapsed < 2880) { // Less than 2 days return '1 day ago'; } else { const daysElapsed = Math.round(minutesElapsed / 1440); return daysElapsed + ' days ago'; } }
このコードは、を使用して、30秒ごとに「時間」を更新します。 クラスのツイート要素があると仮定しています、
、および(setInterval
属性を含む)。
.tweet
.tweet-time
.tweet-user
よくある質問(簡潔な回答がある):created_at
// Auto-refresh interval to update time since tweeted setInterval(() => { console.log('Updating time since...'); const tweets = $('#tweets .tweet'); tweets.each((index, tweetElement) => { $(tweetElement).find('.tweet-time').html(calculateSince($(tweetElement).find('.tweet-user').attr('created_at'))).fadeIn(); }); }, 30000);
Twitter API Authentication(JavaScript): ツイートのスケジューリング(javascript):
catch
リツイート、削除、およびその他のアクションを使用します。 各エンドポイントには特定のパラメーターがあります
/media/upload
およびmedia_id
。/statuses/update
が含まれます
/statuses/retweet/:id
および/statuses/destroy/:id
。/statuses/show/:id
endpointを使用します。応答には、ユーザー情報が含まれます。retweet_count
favorite_count
以上がJavaScriptを使用してツイートしてからTwitter時間を計算しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。