I have a mysql database that has a Date Received entry and a Date Sent entry. I would like to calculate how many hours in between.

This is what I have...

    $strStart = $row['Date_Received'];
    $strEnd   = $row['Date_Sent'];

    $dteStart = new DateTime($strStart);
    $dteEnd   = new DateTime($strEnd); 

    $dteDiff  = $dteStart->diff($dteEnd); 
    print $dteDiff->format("%H:%I:%S"); 

As usual, any help is appreciated.

Recommended Answers

All 4 Replies

$dteStart->diff($dteEnd); returns an instance of DateInterval

If you want the hours from the DateInterval object you can use either of these formatting options, depending on the output you want and a call to DateInterval::format ( string $format )

H - Hours, numeric, at least 2 digits with leading 0 - 01, 02, 23
h - Hours, numeric - 1, 3, 23

echo $dteDiff->format('%h')

Thanks.....this is where I am at now...

$strStart = strtotime( $row['Date_Received'].' +0 hour');   
    $strEnd = strtotime( $row['Date_Sent'].' +0 hour');

    $dteDiff  = $strStart-$strEnd; 

    echo $dteDiff->format('%h');

It returns this error message...
Call to a member function format() on a non-object

Is there a reason you are not using DateTime and trying to use strtotime now?

strtotime is going to return a timestamp, not a DateTime object, so you are not going to be able to use $dteDiff as a DateInterval object like you posted originally.

Thanks...i figured it out. Appreciate your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.