if ($contact->birth_date) {
$birthDate = CRM_Utils_Date::customFormat($contact->birth_date, '%Y%m%d');
if ($birthDate < date('Ymd')) {
- $age = CRM_Utils_Date::calculateAge($birthDate);
+ $deceasedDate = NULL;
+ if (!empty($contact->is_deceased) && !empty($contact->deceased_date)) {
+ $deceasedDate = $contact->deceased_date;
+ }
+ $age = CRM_Utils_Date::calculateAge($birthDate, $deceasedDate);
$values['age']['y'] = $age['years'] ?? NULL;
$values['age']['m'] = $age['months'] ?? NULL;
}
*
* @param date $birthDate
* Birth Date.
+ * @param date $targetDate
+ * Target Date. (show age on specific date)
*
* @return int
* array $results contains years or months
*/
- public static function calculateAge($birthDate) {
+ public static function calculateAge($birthDate, $targetDate = NULL) {
$results = [];
$formatedBirthDate = CRM_Utils_Date::customFormat($birthDate, '%Y-%m-%d');
$birthYear = $bDate[0];
$birthMonth = $bDate[1];
$birthDay = $bDate[2];
- $year_diff = date("Y") - $birthYear;
+ if (empty($targetDate)) {
+ $targetDate = date('Y-m-d');
+ }
+ $targetDate = strtotime($targetDate);
+
+ $year_diff = date("Y", $targetDate) - $birthYear;
// don't calculate age CRM-3143
if ($birthYear == '1902') {
return $results;
}
-
switch ($year_diff) {
case 1:
- $month = (12 - $birthMonth) + date("m");
+ $month = (12 - $birthMonth) + date("m", $targetDate);
if ($month < 12) {
- if (date("d") < $birthDay) {
+ if (date("d", $targetDate) < $birthDay) {
$month--;
}
$results['months'] = $month;
}
- elseif ($month == 12 && (date("d") < $birthDay)) {
+ elseif ($month == 12 && (date("d", $targetDate) < $birthDay)) {
$results['months'] = $month - 1;
}
else {
break;
case 0:
- $month = date("m") - $birthMonth;
+ $month = date("m", $targetDate) - $birthMonth;
$results['months'] = $month;
break;
default:
$results['years'] = $year_diff;
- if ((date("m") < $birthMonth) || (date("m") == $birthMonth) && (date("d") < $birthDay)) {
+ if ((date("m", $targetDate) < $birthMonth) || (date("m", $targetDate) == $birthMonth) && (date("d", $targetDate) < $birthDay)) {
$results['years']--;
}
}
];
}
+ /**
+ * Show age of contact on Deceased date
+ */
+ public function testAgeOfDeceasedContact() {
+ $birthDate = '1961-06-06';
+ $deceasedDate = '1991-07-07';
+ $age = CRM_Utils_Date::calculateAge($birthDate, $deceasedDate);
+ $this->assertEquals('30', $age['years']);
+ }
+
+ /**
+ * Show age of Contact with current date
+ */
+ public function testAgeOfNormalContact() {
+ $birthDate = '1961-06-06';
+ $age = CRM_Utils_Date::calculateAge($birthDate);
+ $this->assertGreaterThanOrEqual('59', $age['years']);
+ }
+
}