maxisme
maxisme

Reputation: 4265

strtotime subtraction not working

I have this PHP code:

echo "time30: ".$time30.'<br />';

echo "time: ".$time.'<br />';

echo date("s",strtotime($time) - strtotime($time30));

Which is returning:

time30: 15/09/2015 20:27:16
time: 15/09/2015 21:08:41
00

Why is it not returning the difference instead of 00?!

Upvotes: 1

Views: 140

Answers (2)

gen_Eric
gen_Eric

Reputation: 227310

Subtracting 2 timestamps doesn't get you a timestamp. It gets you the difference between them. You are then trying to read that difference as a timestamp (or an exact moment in time), and it just to happens to have a "seconds" value of 0.

If you want the number of seconds between these two times, then you just need to do:

echo strtotime($time) - strtotime($time30);

P.S. 15/09/2015 20:27:16 is not a format that strtotime recognizes. I suggest you use DateTime objects for this task.

$time = DateTime::createFromFormat('d/m/Y H:i:s', '15/09/2015 21:08:41');
$time30 = DateTime::createFromFormat('d/m/Y H:i:s', '15/09/2015 20:27:16');

$diff = $time->diff($time30);

$minutes = ($diff->days*24*60) + ($diff->h*60) + ($diff->i);
$seconds = ($minutes*60) + $diff->s;

echo $seconds;  // 2485 (which is 41 minutes, 25 seconds)

Upvotes: 2

Tom
Tom

Reputation: 81

instead of using

$time30= '15/09/2015 20:27:16';
$time= '15/09/2015 21:08:41';

use

$time30= '2015-09-15 20:27:16';
$time= '2015-09-15 21:08:41';

Format has to be correct http://php.net/manual/en/function.strtotime.php

Upvotes: 1

Related Questions