Search code examples
phpdatetimetimedoublehour

Calculate php datetime and convert to hours


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


Solution

  • 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 );
    }