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条)

报告相同问题?

悬赏问题

  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码