dougou2937 2014-10-06 21:54
浏览 42
已采纳

在PHP中将时间戳转换为时间?

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 codes and nothing seems to work for me...

I either get a blank page with no errors (i have error rerposting on my php page), or I get some strange numbers in my page..

so I thought someone here could shed a light on this for me..

Basically I am saving date like so:

$date = date('Y-m-d H:i:s');

I simply save it in mysql database...

and I echo it like so:

 echo $date;

so now what I need to know is how I can convert the echo $date; to something like 1 minutes ago, 10 minutes ago, 1 hour ago etc etc every time the page closes and reopens?

I did try so many functions that I found on google and noon seem to do anything!

could someone please advise on this issue?

Thanks

EDIT:

I used this code as stated in the answer but I still get the $date echo-ed exactly the same way as its stored in the database which is this format: 2014-10-06 22:54:54

$date = date('Y-m-d H:i:s');

$time1 = new DateTime($date);
$now = new DateTime();
$interval = $time1->diff($now);


if ($interval->y) $date = $interval->y . ' years';
elseif ($interval->m) $date = $interval->m . ' months';
elseif ($interval->d) $date = $interval->d . ' days';
elseif ($interval->h) $date = $interval->h . ' hours';
elseif ($interval->i) $date = $interval->i . ' minutes';


echo $date;
  • 写回答

2条回答 默认 最新

  • duanbangzhou7809 2014-10-06 22:09
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?