-2

I just asked a question and got a quick and useful response but this code doesn't seem to be functioning correctly after a few edits.

$firstDate = '2013-09-17 21:20:24';

echo $firstDate;
echo '<br>';

$datetime1 = new DateTime($firstDate);
$datetime2 = new DateTime($secondDate);
$interval  = $datetime1->diff($datetime2);
if ($interval->a <= 7)
{
    if($interval->y !== 0) 
    {
    $elapsed   = $interval->format('%y years ago');
    }
    else
    if($interval->m !== 0) 
    {
    $elapsed   = $interval->format('%m months ago');
    }
    else
    if($interval->a !== 0) 
    {
    $elapsed   = $interval->format('%a days ago');
    }
    else
    if($interval->h !== 0) 
    {
    $elapsed   = $interval->format('%h hours ago');
    }
    else
    if($interval->i !== 0) 
    {
    $elapsed   = $interval->format('%i minutes ago');
    }
    else
    if($interval->S !== 0) 
    {
    $elapsed   = $interval->format('%S seconds ago');
    }

    $elapsed   = str_replace(array('0 years ago', ' 0 months ago', ' 0 days ago',  ' 0 hours ago', ' 0 minutes ago'), '', $elapsed);
$elapsed   = str_replace(array('1 years ago', ' 1 months ago', ' 1 days ago',  ' 1 hours ago', ' 1 minutes ago'), array('1 year ago', '1 month ago', ' 1 day ago', ' 1 hour ago', ' 1 minute ago'), $elapsed);
    echo $elapsed;
}
else 
{
    echo $firstDate;
}

The code is supposed to give the format X days ago or X seconds ago

but it stops working after days so I don't get minutes or seconds. Why is this not working?

Anthony
  • 471
  • 1
  • 5
  • 12

2 Answers2

2

I would suggest that you allow the viewing of errors and notices in your php.ini file for your development server. How to enable notices on my development server

When running the code you provided, I get a Notice: Undefined variable: secondDate on line 11, and Undefined property: DateInterval::$a on line 23.

It seems you are asking PHP to format a number using incomplete data.

Community
  • 1
  • 1
0

It is not working because you are using $interval->a for days and $interval->S for seconds. Correct is $interval->days (for if ($interval->days <= 7)), $interval->d (for if($interval->d !== 0)) and $interval->s (for if($interval->s !== 0)).

See DateInterval for correct parameters.


You can use this code:

Use example :

echo time_elapsed_string('2013-09-01 00:22:35');
echo time_elapsed_string('2013-09-01 00:22:35', true);

Output :

17 days ago
17 days, 1 hour, 40 minutes, 12 seconds ago

Link to the function.

Community
  • 1
  • 1
Glavić
  • 42,781
  • 13
  • 77
  • 107