Reputation: 6788
I have the following PHP datetime object giving strange results:
<?php
$date = new DateTime("2013-01-01");
$date2 = new DateTime("2011-01-01");
$interval = $date2->diff($date);
echo $interval->m;
?>
I am not sure why certain intervals are working and others are not. Any ideas or is this expected? If possible - I would like to continue using DateTime to find this difference but an open to other necessary means.
Upvotes: 1
Views: 2739
Reputation: 106375
See, $interval
is an object, not some primitive value. In your example this interval consists of two years, zero months and zero days. It doesn't get automatically converted into 'interval in months, interval in days' etc. when you're querying its properties: it just returns their values. And it's quite right: should you consider 29 days interval a month interval, for example?
The only exception is $days
property (not $d
!), which actually has a calculated value of days in that interval. And it's quite well described in the documentation:
$days
Total number of days between the starting and ending dates in a DateTime::diff() calculation
Upvotes: 4