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);