douzhenqun1271 2017-07-10 06:08
浏览 193
已采纳

PHP date_diff返回错误的值来比较两个日期时间

I found this post that shows how to get the difference in hours between two dates.

The dates are: 2017-07-03 13:55:20 AND 2017-07-04 21:17:44

When I tried using this code it gives me wrong value:

$date1 = date_create('2017-07-03 13:55:20');

$date2 = date_create('2017-07-04 21:17:44');

$diff = date_diff($date1,$date2);

$hour = $diff->h;

returns 8 hours //incorrect

But this one gives me the correct value:

$hourdiff = round((strtotime('2017-07-03 13:55:20') - strtotime('2017-07-04 21:17:44'))/3600);
returns 31 hours //correct
  • 写回答

3条回答 默认 最新

  • dongxing1965 2017-07-10 06:12
    关注

    You have to go this way:

    <?php
    $date1 = date_create('2017-07-03 13:55:20');
    $date2 = date_create('2017-07-04 21:17:44');
    
    $diff = date_diff($date1,$date2);
    
    $hour = ($diff->d * 24) + $diff->h;
    echo $hour;
    

    demo: http://ideone.com/7SBfHn

    The date_diff function gives you the difference as follow:

                 y  m  d  h  m  s
    -----------------------------
    Date1:    2017-07-03 13:55:20
                 |  |  |  |  |  |
    Diff:        0  0  1  8  0 24
                 |  |  |  |  |  |
    Date2:    2017-07-04 21:17:44
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效