简体   繁体   English

年,月,周,日(星期优先)中的PHP时间前

[英]PHP Time Ago in Years, months, weeks, days (weeks preference)

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. 我一直在寻找创建一个自定义的timefore函数,该函数接受日期并以人类可读的格式返回,这距现在或过去多久了。

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. 但是,我不想使用标准的timeago函数,仅当日期少于20周前时才希望以周和天为单位返回时间。 If the date is over 20 weeks, then it can return the time in years, months, weeks and days as usual. 如果日期超过20周,则可以像往常一样以年,月,周和天为单位返回时间。

The function I have so far is below, but if the date is 9 weeks ago (ie 5th November 2013), it returns the time as 2 months and 2 days ago, rather than 9 weeks ago. 到目前为止,我具有的功能如下,但是如果日期为9周前(即2013年11月5日),它将返回2个月2天前的时间,而不是9周前。

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';
} 

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

demo 演示

link to the function 链接到功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM