我如何操纵日期,使它们以类似的方式显示为“刚刚”...“5 分钟前”...“3 小时前”...“2010 年 6 月 22 日下午 1:45” SO 如何在每个问题的答案/评论旁边显示日期?
更复杂的是,存储在我数据库中的日期是格林威治标准时间(这很好),但我希望它们显示在每个用户浏览器的时区中。
我已经尝试过 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 格式传递“时间”对象,如下所示:
<span class="prettyDate" title='{{ q.date.isoformat }}'>{{q.date.isoformat}}</span>
最佳答案
为什么不在服务器端使用内置模板标签 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 - 如何跨浏览器显示相对绝对日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3119852/