convert time stamp to time ago in php?

前端 未结 2 1661
心在旅途
心在旅途 2021-01-16 21:14

I know this question has been asked several times and I found so many tutorials, blog posts about converting timestamp to ago time in php..

I have tried countless c

2条回答
  •  [愿得一人]
    2021-01-16 21:20

    You should use the DateTime class to get the difference between 2 times, ie;

    $time1 = new DateTime('2014-10-06 09:00:59');
    $now = new DateTime();
    $interval = $time1->diff($now,true);
    

    and then use that difference (which is a DateInterval object, $interval) to find the smallest time difference like this;

    if ($interval->y) echo $interval->y . ' years';
    elseif ($interval->m) echo $interval->m . ' months';
    elseif ($interval->d) echo $interval->d . ' days';
    elseif ($interval->h) echo $interval->h . ' hours';
    elseif ($interval->i) echo $interval->i . ' minutes';
    else echo "less than 1 minute";
    

    which should echo (at time of writing) 13 hours.

    Hope this helps.

提交回复
热议问题