Get years between two dates?
5 answers
As of php 5.3+ you can use DateTime :: diff ()
$a = new DateTime('2009-11-11');
foreach( array('2002-11-11', '2002-11-12', '2005-05-06') as $dt) {
$b = new DateTime($dt);
echo $dt, ' | ', $a->diff($b)->format('%y'), ' | ', $a->diff($b)->format('%y %m %d'), "\n";
}
prints
2002-11-11 | 7 | 7 0 0
2002-11-12 | 6 | 6 11 29
2005-05-06 | 4 | 4 6 5
+4
source to share
I highly recommend using the suggested Sarfraz Ahmed.
If you want to do it manually (and without the new DateTime class), it might look like this:
<?php
$date1 = strtotime("2009-11-11");
$date2 = strtotime("2002-11-11");
$time_difference = $date1 - $date2;
$seconds_per_year = 60*60*24*365;
$years = round($time_difference / $seconds_per_year);
print_r($years);
+5
source to share