drtkyykai004574380
2017-03-14 14:28
浏览 150
已采纳

计算php datetime并转换为小时

I'd like to calculate the difference in hours between two datetimes elements, but I need to have the exact value of it (like a double variable).

How may I do it?

I have no code samples because I got really stucked in this case, I really need the exact hours of this datetime element and I think date_diff can't give this value in a precise way

图片转代码服务由CSDN问答提供 功能建议

我想计算两个日期时间元素之间小时之间的差异,但是我 需要具有它的确切值(如双变量)。

我该怎么办?

我没有代码样本,因为我 我真的需要这个日期时间元素的确切时间,我认为date_diff不能以精确的方式给出这个值

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongxi8297 2017-03-14 14:39
    已采纳

    You seems to look for the getTimestamp method :

    <?php
    
    $date1 = DateTime::createFromFormat('Y-m-d H:i:s', '2016-02-10 07:00:00');
    $date2 = DateTime::createFromFormat('Y-m-d H:i:s', '2017-03-11 19:00:00');
    
    $diff = diff_hours($date1, $date2);
    var_dump($diff);
    function diff_hours(DateTime $date1, DateTime $date2) {
        $diff = $date2->getTimestamp() - $date1->getTimestamp();
        return $diff / ( 60 * 60 );
    }
    
    打赏 评论
  • dpxw17759 2017-03-14 14:57

    You can use below method.

    $date1 = "2014-03-07 05:49:23";
    $date2 = "2014-03-14 05:49:23";
    $seconds = strtotime($date2) - strtotime($date1);
    $hours = $seconds / 60 /  60;
    
    打赏 评论

相关推荐 更多相似问题