【问题标题】:How to display a relative-to-absolute date cross-browsers?如何跨浏览器显示相对绝对日期?
【发布时间】:2011-03-08 09:14:13
【问题描述】:

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

更复杂的是,存储在我的数据库中的日期是 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));
    }

编辑: 我正在将 Python 与 Django 模板(通过 Google Webapp)一起使用,并且我正在以 iso 格式传入“db.DateTimeProperty()”的“时间”对象,如下所示:

<span class="prettyDate" title='{{ q.date.isoformat }}'>{{q.date.isoformat}}</span>

【问题讨论】:

  • 一个只随便用过Date的人的问题:不能用setUTC*()方法设置日期吗?它不会自动转换为当地时间吗?
  • 谢谢,我可以试试。但是,这仍然对跨浏览器部分没有帮助,这确实是这里更大的问题。

标签: javascript jquery django cross-browser


【解决方案1】:

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

在相对时间中,时区没有意义,只要您区分的 2 次在同一个区域内。对于过去更远的结果,并且您想以绝对时间呈现,您必须自己进行时间转换。为此,您必须 ask the user for her timezone (or use some JS on a previous page to send it to you) 并将其存储在用户配置文件中。

这也在in the mailing list讨论。

【讨论】:

  • 主要是因为我希望时间显示在用户浏览器的时区设置中。我也喜欢 JavaScript 的想法,因为上面的插件每 10 秒自动更新一次日期,所以如果用户让他们的浏览器保持打开状态,它就会有更新的文本。
  • 编辑了一些关于在服务器端选项中转移到正确区域的内容。
  • 嗯,我以前不想询问用户他的时区,因为那些没有帐户的公共用户将查看该网站。我会考虑/查看您提供的通过 JS 从上一页发送时区的链接,尽管我仍然更喜欢自动更新的跨浏览器 JS 解决方案。
猜你喜欢
  • 2012-06-05
  • 1970-01-01
  • 2019-03-14
  • 2016-01-10
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
  • 2011-10-02
  • 1970-01-01
相关资源
最近更新 更多