此JavaScript代碼使用Twitter API的search.json響應中的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秒以來的“時間”。 它假設您具有class,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):
使用oauth 2.0與Twitter開發人員Portal的JSOAUTH和API鍵的庫2.0。catch
> endpoint中包含/media/upload
等)。 每個端點都有特定的參數。 media_id
/statuses/update
/statuses/retweet/:id
>回复推文:/statuses/destroy/:id
使用/statuses/show/:id
獲取推文作者:retweet_count
使用favorite_count
> endpoint;響應包括用戶信息。 以上是自從使用JavaScript推文以來,計算Twitter時間的詳細內容。更多資訊請關注PHP中文網其他相關文章!