Creating a calculated field to count days until a date

This kept me busy for hours until I figured out that dates in beans are strings formatted as per user preferences. I’m using UK format so the code failed. Sugar provides a global variable $GLOBALS [ ā€˜timedate’ ] which is a TimeDate with the current user’s format and a convenience function to create a SugarDateTme from the user-formatted date string. SugarDateTime is derived from a DateTime…


if ($bean->birthdate != null){
	// Create a SugarDateTime from user-formatted date
	$birthDate = $GLOBALS['timedate']->fromString($bean->birthdate);
	$today = new SugarDateTime();
	if ($today > $birthDate) {
		$bean->age_year_calc = $today->diff($birthDate)->y;
	}
	else {
		$bean->age_year_calc = "Error";
	}
} else {
	$bean->age_year_calc = "N/A";
}

I hope this saves some time. For some reason the forum does not display the variable properly in text. The crucial line is:

$birthDate = $GLOBALS['timedate']->fromString($bean->birthdate);