fbpx

Sometimes you need to calculate a person’s age on the fly, but on a given date, not today’s.

This is especially useful in Formidable Pro Views, where you can use Formidable shortcodes to populate the date variables.

/********************************************************************************
 * erentzen@gmail.com
 * function calculate_years_diff($atts = array( 'birthdate' => 'Y-m-d','effective' => 'Y-m-d')
 * calculates difference in years between two dates
 * can be called by shortcode 
 ********************************************************************************/
add_shortcode('calculate_age','calculate_years_diff');
function calculate_years_diff($atts) {
	$defaults = array(
		'birthdate' => false,
		'effective' => false
	);
	$atts = shortcode_atts($defaults, $atts, 'calculate_age');
	extract($atts);
	if( false === $birthdate || false === $effective ) {
		return;
	} else {
		
		$birthdate 	= new DateTime( $birthdate );
		$effective 	= new DateTime( $effective );	
		$interval 	= $birthdate->diff($effective);
		$age 		= $interval->y;
	}
	
	return $age;
}