user123_456
user123_456

Reputation: 5795

TIMEDIFF() function in PHP?

Is there any PHP function that does the same thing as SQL function TIMEDIFF() ?

Here is my code:

$to_time = array_search( 'time2.Time', $aCols );
$from_time = array_search( 'time1.Time', $aCols );
$value= ;  

I need to get values in this format HH:MM:SS

I use this version : PHP 5.2.17

Upvotes: 1

Views: 12449

Answers (4)

Horen
Horen

Reputation: 11382

If you use php 5.3 or after you can use the following code

$to_time = new DateTime(array_search( 'time2.Time', $aCols ));
$from_time = new DateTime(array_search( 'time1.Time', $aCols ));
$interval = $date1->diff($date2);
$value = $interval->format('%H:%i:%s');

or before 5.3 try something like this:

$date1 = strtotime("2012-09-13 12:14:24.453");
$date2 = strtotime("2012-09-15 14:21:28.453");
$interval = $date2 - $date1;
$seconds = $interval % 60;
$minutes = floor(($interval % 3600) / 60);
$hours = floor($interval / 3600);
echo $hours.":".$minutes.":".$seconds;

http://codepad.viper-7.com/b9b0L5

Upvotes: 1

Get your time in "H:i:s" format, keep a start date as 00:00:00 its easy by strtotime()

   <?php
    $origin   = '00:00:00';
    $fromTime = '00:16:00'; // $fromTime = date('H:i:s',strtotime($from_time))
    $toTime = '00:45:00';  //// $toTime= date('H:i:s',strtotime($to_time))

    $diff = (strtotime($toTime) - strtotime($fromTime)) + strtotime($origin);

    echo date('H:i:s', $diff );

output : 00:29:00

Upvotes: 0

Baba
Baba

Reputation: 95101

You can try

$dattTime = new DateTime();
$dateTime2 = new DateTime("2012-09-11 10:25:00");


$interval = $dattTime->diff($dateTime2);
var_dump($interval->format('%H:%i:%s'));



$hours = $interval->h + ($interval->d*24);
var_dump("Total Hours: " . $hours . " hrs");  

Output

string '08:17:15' (length=8)
string 'Total Hours: 608 hrs' (length=20)

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Use strtotime() if needed to convert the values to timestamps (which they should already be ideally) and then just subtact the two.

Upvotes: 0

Related Questions