tags:

views:

77

answers:

6

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?

+2  A: 

Here is extremely handy function by addedbytes

Sarfraz
+4  A: 

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
VolkerK
A: 

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() )

Gausie
+3  A: 

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);
FlorianH
+1  A: 
$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.

Matěj Grabovský
A: 

Assuming the dates are UNIX timestamps (Unix Epoch), "probably" the fastest way you could do this would be:

intval(($time2 - $time1) / 31556926);
Lachlan McDonald