0

每次用户执行特殊操作时,我都有一个脚本保存时间戳(使用 time() 函数)。

我想以易于阅读的用户方式在页面上显示用户多久以前执行此操作。我目前得到它来显示它大约是多少小时前,但我希望它以如下方式返回:

1天5小时30分钟...

4

3 回答 3

1

为了实现你想要的,你可以简单地做

$target = strtotime("Feb 7 2013 2:15 AM");
$now = time();
$diff = $now - $target;
$days = floor(($diff)/24/60/60);
$hours = floor(fmod($diff, 24*60*60)/60/60);
$minutes = floor(fmod(fmod($diff, 24*60*60),60*60)/60);
echo $days . " days " . $hours . " hours " . $minutes . " minutes"; // e.g. "2 days 14 hours 54 minutes"

更通用的解决方案

function timeago($timestamp) {

    // Predefine variables
    $timeago = '';
    $past = FALSE;
    $future = FALSE;
    $prefixAgo = NULL;
    $prefixFromNow = NULL;
    $suffixAgo = "ago";
    $suffixFromNow = "from now";
    $wordSeperator = " ";

    // Current time
    $current = time();

    // Seconds ago
    $seconds = abs($current - $timestamp);

    // Determine whether the time is in the future or the past
    if ($current >= $timestamp) {
        $past = TRUE;
    } else {
        $future = TRUE;
    }

    // Calculate time ago in different formats
    $minutes = $seconds / 60;
    $hours = $minutes / 60;
    $days = $hours / 24;
    $months = $days / 30;
    $years = $days / 365;

    // Format time ago according to calculated time
    if      ($seconds < 45) { $timeago = "less than a minute"; }
    else if ($seconds < 90) { $timeago = "about a minute"; }
    else if ($minutes < 45) { $timeago = round($minutes) . " minutes"; }
    else if ($minutes < 90) { $timeago = "about an hour"; }
    else if ($hours < 24)   { $timeago = "about " . round($hours) . " hours"; }
    else if ($hours < 42)   { $timeago = "a day"; }
    else if ($days < 30)    { $timeago = round($days) . " days"; }
    else if ($days < 45)    { $timeago = "about a month"; }
    else if ($days < 365)   { $timeago = round($months) . " months"; }
    else if ($years < 1.5)  { $timeago = "about a year"; }
    else                    { $timeago = round($years) . " years"; }

    // Append prefix and suffix
    if (!empty($prefixAgo))     { $prefixAgo        = $prefixAgo . $wordSeperator; }
    if (!empty($suffixAgo))     { $suffixAgo        = $wordSeperator . $suffixAgo; }
    if (!empty($prefixFromNow)) { $prefixFromNow    = $prefixFromNow . $wordSeperator; }
    if (!empty($suffixFromNow)) { $suffixFromNow    = $wordSeperator . $suffixFromNow; }
    if ($past)                  { $timeago = $prefixAgo . $timeago . $suffixAgo; }
    if ($future)                { $timeago = $prefixFromNow . $timeago . $suffixFromNow; }

    // Return results
    if (!empty($timeago)) {
        return $timeago;
    } else {
        return NULL;
    }

}
于 2013-02-09T16:56:30.110 回答
0
echo date('Y-m-d', time()); 

显示 2013-02-09
还可以查看manual , date('Ymd H:i:s', time()); 将输出 2013-02-09 17:57:30

于 2013-02-09T16:55:58.157 回答
0

试试看:

$diff = date_diff($lastaccess, new DateTime(date('d-m-Y'));
echo $diff->format('Last access on: %s seconds %d days %m months and %y years ago')};
于 2013-02-09T16:57:30.313 回答