0
votes

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
I don't see any 20's in your code where are you checking for the 20 weeks thing?ahmad
try to do it, and we will help if doesn't workPablo Martinez

1 Answers

3
votes

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