user2826499
user2826499

Reputation: 121

PHP: subtract time

Here's my code for subtracting a time...but the problem here its not subtracting also the seconds..

fldFullTime and fldTotalDuration are came from in my database..

Assuming the fldFullTime is 10:00:00

then for fldTotalDuration is 08:30:00

$fulltime = new DateTime($row['fldFullTime']);
$totalduration = new DateTime($row['fldTotalDuration']);

$res= $fulltime ->diff($totalduration);
echo "DIFF: ".$res->format("%H:%S");

The result the I get for this code is 01:00

So, when I subtract the fldFullTime [10:00:00] to fldTotalDuration [08:30:00] the result should be is 1:30:00

How can I make it?

Thanks for the help

Upvotes: 2

Views: 333

Answers (5)

zessx
zessx

Reputation: 68790

You're using a wrong format string :

  • %H : hours
  • %S : seconds

You need to add minutes :

$fulltime = new DateTime('10:00:00');
$totalduration = new DateTime('08:30:00');
$res= $fulltime ->diff($totalduration);

echo "DIFF: ".$res->format("%H:%S");
//DIFF: 01:00
echo "DIFF: ".$res->format("%H:%I:%S");
//DIFF: 01:30:00

Upvotes: 4

Zword
Zword

Reputation: 6793

I have done it using explode:

$fulltime = new DateTime($row['fldFullTime']);
$totalduration = new DateTime($row['fldTotalDuration']);

$piece1 = explode(":", $fulltime);
$piece2 = explode(":", $totalduration);

$hours=$piece2[0]-$piece1[0];
$min=$piece2[1]-$piece1[1];
$sec=$piece2[2]-$piece1[2];

Echo "$hours:$min:$sec";

Upvotes: -1

naveen goyal
naveen goyal

Reputation: 4629

you are missing 'i' which shows the minute.

$fulltime = new DateTime('10:00:00');
$totalduration = new DateTime('08:30:00');

$res= $fulltime->diff($totalduration);
echo "DIFF: ".$res->format("%H:%i:%S");

Upvotes: 3

SlyChan
SlyChan

Reputation: 769

In your case the format should be %H:%I:%S

See DateInterval::format documentation.

Upvotes: 3

Mahmood Rehman
Mahmood Rehman

Reputation: 4331

check this :

  $fulltime = new DateTime('10:00:00');
$totalduration = new DateTime('08:30:00');

$res= $fulltime ->diff($totalduration);
echo "DIFF: ".$res->format("%H:%I:%S");

Upvotes: 3

Related Questions