troubleshooting Question

# PHP Function To Calculate Birthdate asked on
PHP
I need to create a birthdate and I am only given the name of the birth month and the age. I am setting the day number to 1 because that is not given.

In other words, if I am given, "May" for the birth month and 28 for the age I would end up with 5/1/1982.  If I am given April and 28, then the birthdate would be 4/1/1983.

Below is what I have come up with and it is currently working. My question is about making this function less verbose if possible.

``````echo calculateBirthDate('april',28);     #  4/1/1993  given current month is May
echo calculateBirthDate('may',28);       #  4/1/1992  given current month is May
echo calculateBirthDate('mayxyz',28);    #  NULL  given current month is May
echo calculateBirthDate('may',x1x);      #  NULL  given current month is May

function calculateBirthDate(\$monthName,\$age){

//CONVERT BIRTH MONTH NAME TO INTEGER

\$d = date_parse(\$monthName);
\$birthMonthNumber = \$d['month'];

//IF DATA IS BAD, RETURN NULL
if(!\$birthMonthNumber){
return NULL;
}
if(is_numeric(\$age)){
\$age = intval(\$age);
} else {
return NULL;
}

//DETERMINE BIRTH YEAR
\$currentYear = date("Y");
\$currentMonth = date("n");

if( \$birthMonthNumber >= \$currentMonth ){ //IF BIRTH MONTH IS CURRENT OR IN THE FUTURE, THE BIRTH YEAR SHOULD BE 1 YEAR LESS THAN IF THE BIRTH MONTH HAS ALREADY  OCCURRED.

\$birthYear = (\$currentYear - \$age) -1;

} else {

\$birthYear = \$currentYear - \$age;

}

//CREATE DATE STRING USING 1 AS THE DAY

\$dateString = \$birthMonthNumber . '/1/' . \$birthYear;

return \$dateString;

}
``````

Daniel PineaultPresident / Owner CARDA Consultants Inc.
###### Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.