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

  • 写回答

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 );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?