convert time stamp to time ago in php?

前端 未结 2 1645
心在旅途
心在旅途 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:14

    Check this function intval() - http://php.net/manual/en/function.intval.php The following code should help you out

    $seconds_ago = (time() - strtotime('2014-01-06 15:25:08'));
    
    if ($seconds_ago >= 31536000) {
        echo "Seen " . intval($seconds_ago / 31536000) . " years ago";
    } elseif ($seconds_ago >= 2419200) {
        echo "Seen " . intval($seconds_ago / 2419200) . " months ago";
    } elseif ($seconds_ago >= 86400) {
        echo "Seen " . intval($seconds_ago / 86400) . " days ago";
    } elseif ($seconds_ago >= 3600) {
        echo "Seen " . intval($seconds_ago / 3600) . " hours ago";
    } elseif ($seconds_ago >= 60) {
        echo "Seen " . intval($seconds_ago / 60) . " minutes ago";
    } else {
        echo "Seen less than a minute ago";
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题