plumby101
plumby101

Reputation: 133

PHP - Difference between two times

I've created a timing system for a charity race. I'm trying to find the difference between the start time and the finishers time using PHP. I'm not sure I'm recording the times correctly, but this is the start time i just recorded...

20180808180653

And this is a finisher time...

20180808180654

The difference between them is roughly 1 hour 24, but when i use...

date('h:i:s', $finshTime-$startTime)

I get 03:24:20 not 01:34:20.

Can someone please help?

Upvotes: 0

Views: 75

Answers (2)

berramou
berramou

Reputation: 1471

First check if the type of $finshTime and $startTime are integer.
you can use get variable type:

 gettype($startTime);

if this is the case try this with ():

$diff_date = date('h:i:s', ($finshTime - $startTime) );

if $startTime and $finshTime are string try this:

$diff_date = date('h:i:s', (strtotime($finshTime) - strtotime($startTime)) );

Upvotes: 0

ficuscr
ficuscr

Reputation: 7054

The date method accepts as "integer Unix timestamp". You are supplying instead a number of seconds (1 in your example).

$start = '20180808180653';
$end = '20180808180654';

$diff = $end - $start;
var_dump($diff);         //1

$d = date('h:i:s', $$diff);
var_dump($d);            //04:00:01

//the above is wrong. You need to try something like the code below   

$dStart = new DateTime($start);
$dEnd = new DateTime($end);
$interval = $dStart->diff($dEnd);
var_dump($interval->format('%h:%i:%s'));

I'd be leery using a string representation of a datetime that looks like that. Convert the whole thing into a date format that makes sense like yyyy-mm-dd hh:mm:ss, or a valid unix time stamp.

Your first approach isn't that far off, you just need to use a strtotime function. I'd guarantee that you can first make an accurate Date or Unix time representation of those strings you are using. Rest should fall into place.

Upvotes: 3

Related Questions