ive got 2 dates like:
2009-11-11 2002-11-11
and i want to get the years between them '7'. how should i do that? the month and day will always be identical and i dont want to use -. is there a appropiate way for this?
ive got 2 dates like:
2009-11-11 2002-11-11
and i want to get the years between them '7'. how should i do that? the month and day will always be identical and i dont want to use -. is there a appropiate way for this?
With 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
If the dates will indeed always be the same you could use this:
$date1 = "2009-11-11";
$date2 = "2002-11-11";
$years = substr($date1,0,4) - substr($date2,0,4); // 7
Alternatively, convert them to timestamp (mktime), subtract then convert back (using an argument on date() )
I strongly recommend using the function Sarfraz Ahmed suggested.
If you want to do it by hand (and without the new DateTime class), it may 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);
$a = new DateTime('2009-11-11');
$b = new DateTime('2002-11-11');
$years = $b->diff($a)->y;
var_dump($years); // int(7)
Hope this helps.
Assuming the dates are UNIX timestamps (Unix Epoch), "probably" the fastest way you could do this would be:
intval(($time2 - $time1) / 31556926);