drl47263 2013-10-27 12:47
浏览 24
已采纳

PHP - 2个日期之间的差异,返回0

$from_time = date('Y-m-d H:i:s');
$to_time = $row['clock'];

echo  $from_time - $to_time;

The $to_time is a time stamp in the MySQL database. $row['clock'] = 2013-10-27 13:28:01.

When I run this code, the echo always returns 0.

I am trying to get the amount of seconds between the dates.

  • 写回答

3条回答 默认 最新

  • dttwois6098 2013-10-27 12:51
    关注

    You're basically trying to subtract two strings. If you echo $from_time, you can find out that the value will be something like 2013-10-27 12:49:270, and $to_time will be another string -- 2013-10-27 13:28:01.

    You need to convert them into timestamps before doing the substraction:

    $from_time = time();
    $to_time = strtotime($row['clock']);
    

    I recommend using the DateTime class for working with dates and times.

    This is how you find the difference between two dates using DateTime class:

    $from_time = new DateTime('now');
    $to_time = new DateTime("2013-10-27 13:28:01");
    $interval = $from_time->diff($to_time);
    echo $interval->format('%h hours %i minutes %S seconds');
    

    Output:

    0 hours 31 minutes 48 seconds
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作