When using this answer from this thread. It fails for me, I checked the $now, $ago, $diff
and $string
and they all work or in proper condition.
public static function convertTime($datetime)
{
$now = new DateTime;
$now->setTimezone(new DateTimeZone('Asia/Manila'));
$now->format('Y-m-d h:i:s');
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = [
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second'
];
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
}
Why does it fail:
If I var_dump($diff->$k)
, it returns all the value to me is 0, making it null; the only problem is why?