Dmitry Makovetskiyd Dmitry Makovetskiyd - 3 months ago 12
PHP Question

Subtracting two dates in php

I have got two dates in php

$date1 = 'May 3, 2012 10:38:22 GMT'

$date2 = '06 Apr 2012 07:22:21 GMT'


Then I subtract both of them

$date2 - $date1


, and get

Result:6


Why is the result 6 and not 27? ... ? How can I subtract the two dates, and make it return me a result based on month differences while subtracting the years & days & time ?

Answer

Part 1: Why is the result 6?

The dates are simply strings when you first subtract them. PHP attempts to convert them to integers. It does this by converting until the first non-number. So, date2 become 6 and date1 becomes 0.

Part 2: How do you get it to work?

$datetime1 = strtotime('May 3, 2012 10:38:22 GMT');
$datetime2 = strtotime('06 Apr 2012 07:22:21 GMT');

$secs = $datetime2 - $datetime1;// == <seconds between the two times>
$days = $secs / 86400;

Convert as appropriate.

Comments