doutou6803 2014-01-07 13:13
浏览 56
已采纳

PHP时间前几年,几个月,几周,几天(周偏好)

I've been looking at creating a customised time ago function which accepts a date and returns in human readable format how long ago this was in the past or future.

Rather than use a standard timeago function though, I want this to return the time in Weeks and Days only if the date is less than 20 weeks ago. If the date is over 20 weeks, then it can return the time in years, months, weeks and days as usual.

The function I have so far is below, but if the date is 9 weeks ago (i.e. 5th November 2013), it returns the time as 2 months and 2 days ago, rather than 9 weeks ago.

function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);

$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;

$string = array(
    'y' => 'year',
    'm' => 'month',
    'w' => 'week',
    'd' => 'day',
);
foreach ($string as $k => &$v) {
    if ($diff->$k) {
        $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
    } else {
        unset($string[$k]);
    }
}

if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' old' : 'just now';
} 
  • 写回答

1条回答 默认 最新

  • doumangzhen7204 2014-01-07 13:31
    关注

    You could just replace:

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;
    

    with:

    if (20 > $diff->days / 7) {
        $diff->y = $diff->m = $diff->h = $diff->i = $diff->s = 0;
        $diff->w = floor($diff->days / 7);
        $diff->d = $diff->days - $diff->w * 7;
    } else {
        $diff->w = floor($diff->d / 7);
        $diff->d -= $diff->w * 7;
    }
    

    <kbd>demo</kbd>

    <kbd>link to the function</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?