首页 > web前端 > js教程 > 自从使用JavaScript推文以来,计算Twitter时间

自从使用JavaScript推文以来,计算Twitter时间

尊渡假赌尊渡假赌尊渡假赌
发布: 2025-02-26 01:49:10
原创
834 人浏览过

此JavaScript代码使用Twitter API的search.json响应中的属性来计算创建推文以来经过的时间。 这对于在Twitter小部件或类似应用程序上显示“时间”很有用,并且可以使用created_at>。setInterval刷新

Calculate Twitter Time Since Tweet using JavaScript

函数:calculateSince

此功能采用DateTime字符串(例如,“ Tue,2012年6月12日)06:24:59 0000”),并返回一个代表经过时间的人类可读字符串。

> 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。
  • >调度推文(JavaScript):不直接由Twitter API支持。 基于浏览器的JavaScript解决方案受浏览器正常运行时间的限制。> >
  • 错误处理(推文发布):
  • >使用块,承诺在推文发布期间处理错误。 在推文中包含图像:
  • >:>使用端点上传,然后在catch> endpoint中包含
  • >。
  • 转发,删除和其他操作:对这些操作使用适当的Twitter API端点(/media/upload等)。 每个端点都有特定的参数。media_id /statuses/update
  • >检索转发/喜欢计数:使用/statuses/retweet/:id>回复推文:/statuses/destroy/:id使用
  • /statuses/show/:id获取推文作者:retweet_count使用favorite_count> endpoint;响应包括用户信息。
  • >此修订后的响应提供了代码和答案的更简化和改进的版本。 切记用实际的DOM元素选择器替换占位符选择器。>

以上是自从使用JavaScript推文以来,计算Twitter时间的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板