我该如何操作日期以使它们显示为“刚才”...“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));
}
编辑: 我使用Python和Django模板(通过谷歌的webapp),和“时间”的对象我“M处于开通‘db.DateTimeProperty()’在ISO格式,像这样:
<span class="prettyDate" title='{{ q.date.isoformat }}'>{{q.date.isoformat}}</span>
来自某人只是随便使用Date的问题:你不能使用setUTC *()方法设置日期吗?它不会自动转换为当地时间吗? – brainjam 2010-06-25 23:01:56
谢谢,我可以尝试做到这一点。但是,这仍然不能帮助跨浏览器部分,这实际上是更大的问题。 – Cuga 2010-07-02 16:14:06