Skip to content

Instantly share code, notes, and snippets.

@Victa
Forked from banksy89/Years between two dates
Created August 30, 2012 07:30
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Victa/3523765 to your computer and use it in GitHub Desktop.
Save Victa/3523765 to your computer and use it in GitHub Desktop.
Get the number of years between two dates using PHP DateTime class
// My Birthday :)
$date_1 = new DateTime( '1989-06-15' );
// Todays date
$date_2 = new DateTime( date( 'Y-m-d' ) );
$difference = $date_2->diff( $date_1 );
// Echo the as string to display in browser for testing
echo (string)$difference->y;
/**
* In a function
*/
function yearsMonthsBetween ( $date1, $date2 ) {
$d1 = new DateTime( $date1 );
$d2 = new DateTime( $date2 );
$diff = $d2->diff( $d1 );
// Return array years and months
return array ( 'years' => $diff->y, 'months' => $diff->m );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment