Get years between two dates?

I have 2 dates:

2009-11-11 2002-11-11

and I want to get years in between "7". how should i do it? the month and day will always be the same and I don't want to use them. is there a suitable way to do this?

0


source to share


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


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


$a = new DateTime('2009-11-11');
$b = new DateTime('2002-11-11');
$years = $b->diff($a)->y;
var_dump($years); // int(7)

      

Hope it helps.

+1


source


If the dates will always be the same, you can 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 the argument to date ())

0


source


Assuming the dates are UNIX (Unix Epoch) timestamps, "perhaps" the fastest way you could do this is:

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

      

0


source







All Articles