Voriki
Voriki

Reputation: 1637

PHP time subtraction not functioning

I'm trying to display the time x started, the time x finished, and how long x took to complete. I have the start and end displaying correctly, but the following subtraction gives me a bonkers answer.

    // to unix timestamps for subtraction
    $startTime = strtotime($row['bp_rec_start']);
    $endTime = strtotime($row['bp_rec_end']);
    $timeTaken = $endTime - $startTime;

    //back to date formats
    $startTime = date('H:i',$startTime);
    $endTime = date('H:i',$endTime);
    $timeTaken = date('H:i',$timeTaken);

e.g. ( 01:24 - 01:23 = 07:01)

Thanks

Upvotes: 2

Views: 196

Answers (1)

deceze
deceze

Reputation: 522005

Timestamps are seconds since 1970, each timestamp representing an absolute point in time. So $endTime - $startTime produces some point in time like 1975-04-12 07:01:52. Printing the hour and minute part of that will of course print 07:01. The timestamp itself though is the difference in seconds, so you can do:

echo "Difference: $timeTaken seconds";

You should of course look into DateInterval (look at the 3rd example).

Upvotes: 4

Related Questions