Get years between two dates using DateTime
Using PHP's 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 );
}
Written by Ashley Banks
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Related Tags
#php
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#