Making a PHP/MySQL Timestamp look more attractive

烂漫一生 提交于 2019-12-04 19:10:52

This is best done on the client side in the presentation layer. Here is a JS solution:

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 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>

into something like this:

<abbr class="timeago" title="July 17, 2008">about a year ago</abbr>

To convert the date into the ISO 8601 format you can do something like this:

<?= date("c", $post_date) ?>

Examples:

You opened this page less than a minute ago. (This will update every minute. Wait for it.)

This page was last modified 11 days ago.

Ryan was born 31 years ago.

$ts = new DateTime();
$ts->setTimestamp($my_timestamp);
$cur = new DateTime();
$difference = $cur->diff($ts);
if ($difference->format("%a") == 0)
    $out = $difference->format("%h hours %i minutes");
elseif ($difference->format("%a") < 7)
    $out = $difference->format("%a days");
elseif ($difference->format("%m") == 0) {
    $days = $difference->format("%a");
    $out = sprintf("%d weeks %d days", floor($days / 7),
        $days % 7);
}
elseif ($difference->format("%y") == 0)
    $out = $difference->format("%m months");
else
    $out = "over a year";

You'll have to make a few adjustments if you don't want stuff like "1 days".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!