Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Get Age from BuddyPress datebox field data
* Get Age from BuddyPress date of Birth
* @param string $dob_field_name :name of the DOB field in xprofile, like Dob or Date of Birth
* @param int $user_id : the user for which you want to retrieve the age
* @param string $format: the way you want to print the difference, look t <> for the acceptable agrs
* @return string :the formatted age in year/month
function bpdev_get_age_from_dob($dob_field_name,$user_id=false,$format="%y Years, %m Month(s), %d days"){
$user_id=bp_displayed_user_id ();
$dob_time=xprofile_get_field_data($dob_field_name, $user_id);//get the datetime as myswl datetime
$dob=new DateTime($dob_time);//create a DateTime Object from that
$current_date_time=new DateTime();//current date time object
//calculate difference
$diff= $current_date_time->diff($dob);//returns DateInterval object
//format and return
return $diff->format($format);
echo "Your Age".bpdev_get_age_from_dob("Dob",bp_loggedin_user_id());
//and so on

This comment has been minimized.

Copy link

eliasfaical commented Mar 9, 2016

I got an error when put in echo:
Fatal error: Call to undefined method DateTime::diff() in /home/dom/public_html/wp-content/plugins/buddypress/bp-themes/bp-default/functions.php on line 377

Line 377 is this – $diff= $current_date_time->diff($dob);//returns DateInterval object

Any idea how to correct that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.