如何显示相对于绝对日期的跨浏览器?

Cug*_*uga 6 javascript django jquery cross-browser

我如何操纵日期,以便它们显示为"刚刚"..."5分钟前"..."3小时前"..."2010年6月22日下午1:45"以类似的方式如何SO显示每个问题的答案/评论旁边的日期?

更复杂的是,我的数据库中存储的日期是GMT时间(很好),但我希望它们出现在每个用户浏览器的时区中.

我已经尝试了John Resig的漂亮日期插件:http://bassistance.de/jquery-plugins/jquery-plugin-prettydate/,我编辑了它,以便从数据库中的GMT时间中减去时区偏移量.但是,此解决方案仅适用于FireFox.

在添加时区偏移后,这是'prettydate'函数:

format : function(time) {
var date = new Date(time);
var currentDate = new Date();
var timezoneOffsetInMilliseconds = currentDate.getTimezoneOffset() * 60000;
var currentTimeInMillisecondsUtc = currentDate.getTime();
var givenTimeInMillisecondsUtc = date.getTime()- timezoneOffsetInMilliseconds;
var diffInSeconds = ((currentTimeInMillisecondsUtc - givenTimeInMillisecondsUtc) / 1000);
var day_diff = Math.floor(diffInSeconds / 86400);

if (isNaN(day_diff) || day_diff < 0)
    return;

        // If longer than a month, calculate the date w/ timezone offset
        if (day_diff >= 31)
            return new Date(givenTimeInMillisecondsUtc).toLocaleString();

        var messages = $.prettyDate.messages;
        return day_diff == 0 && (diffInSeconds < 60 && messages.now 
            || diffInSeconds < 120 && messages.minute
             || diffInSeconds < 3600
             && messages.minutes(Math.floor(diffInSeconds / 60))
            || diffInSeconds < 7200 && messages.hour || diffInSeconds < 86400
            && messages.hours(Math.floor(diffInSeconds / 3600)))
            || day_diff == 1 && messages.yesterday || day_diff < 7
            && messages.days(day_diff) || day_diff < 31
            && messages.weeks(Math.ceil(day_diff / 7));
    }
Run Code Online (Sandbox Code Playgroud)

编辑:我正在使用带有Django模板的Python(通过Google Webapp),以及我以iso格式传递'db.DateTimeProperty()'的'time'对象,如下所示:

<span class="prettyDate" title='{{ q.date.isoformat }}'>{{q.date.isoformat}}</span>
Run Code Online (Sandbox Code Playgroud)

Ofr*_*viv 2

为什么不使用内置模板标签timesince或自定义模板标签在服务器端执行此操作?

在相对时间中,时区没有意义,只要您比较的两次时间位于同一时区即可。对于距离较远的过去的结果,并且您希望将其呈现为绝对时间,您必须自己进行时间平移。为此,您必须询问用户她的时区(或使用上一页上的一些 JS 将其发送给您)并将其存储在用户配置文件中。

这也在邮件列表中进行了讨论。