问题描述
所以基本上,我目前正在从MySQL数据库中选择一个时间戳.在数据库中,时间戳看起来像这样:
So basically, I'm currently selecting a Timestamp from my MySQL database. In the database, the timestamp looks like so:
2010-06-30 12:36:08
对于Web应用程序来说,显然这对用户查看不是很有吸引力.因此,使用一些CodeIgniter函数,我使它看起来更好一些.
Obviously for a webapp, that's not very attractive for users to view. So, using some CodeIgniter functions, I made it look a bit nicer.
<h4 class="timestamp">
<?php // Quickly calculate the timespan
$post_date = mysql_to_unix($row->date);
$now = time();
echo timespan($post_date, $now);?> ago
</h4>
如果您不使用CodeIgniter,则除echo timespan()
以外的所有内容都是标准PHP. CodeIgniter只是将其作为英语"时间跨度来回应.因此,示例输出为:
If you don't do CodeIgniter, everything's standard PHP except for echo timespan()
. CodeIgniter just echoes it as an 'English' timespan. So, an example output would be:
2 Months, 4 Weeks, 5 Hours, 20 Minutes ago
这一切都很好,但是,我想让它看起来仍然更好……逗号太多,而且时间太长了(我知道,我很挑剔……).我想喜欢的是:
That's all well and good, but, I want to make it seem nicer still... there are too many commas and its all a tad too long (I know, I'm picky...). What I'd like is:
- 如果时间间隔不到一天,则输出应为
7 hours, 33 minutes ago
- 如果时间跨度不到一周,则输出应为
4 days ago
- 如果时间间隔不到一个月,则输出应为
2 weeks, 6 days ago
- 如果时间跨度超过一个月,则输出应为
4 months ago
- 如果时间跨度超过一年,则输出应为
Over a year ago
- If the timespan is less than a day old, the output should be
7 hours, 33 minutes ago
- If the timespan is less than a week old, the output should be
4 days ago
- If the timespan is less than a month old, the output should be
2 weeks, 6 days ago
- If the timespan is over a month old, the output should be
4 months ago
- In the eventual case of the timespan being over a year old, the output should be
Over a year ago
如您所见,我目前正在使用CodeIgniter函数来简化此操作-但是,如果有任何本机PHP函数可以执行我想要的操作,那将会很棒.
As you can see, I'm currently using a CodeIgniter function to simplify this - but if there's any native PHP function that can do what I want it to, that'll be awesome.
感谢您的帮助!
杰克
推荐答案
最好在表示层的客户端进行此操作.这是一个JS解决方案:
Timeago 是一个jQuery插件,可轻松支持自动更新模糊时间戳(例如"4分钟"前"或大约1天前").
Timeago is a jQuery plugin that makes it easy to support automatically updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
Timeago将使用class
的timeago和title
中的ISO 8601时间戳来转换所有abbr元素:
Timeago will turn all abbr elements with a class
of timeago and an ISO 8601 timestamp in the title
:
<abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr>
变成这样:
<abbr class="timeago" title="July 17, 2008">about a year ago</abbr>
要将日期转换为ISO 8601格式,您可以执行以下操作:
<?= date("c", $post_date) ?>
示例:
此页面的最后修改时间为11天 以前.
This page was last modified 11 days ago.
Ryan出生于31年前.
Ryan was born 31 years ago.
这篇关于使PHP/MySQL时间戳更具吸引力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!