troubleshooting Question

PHP Function To Calculate Birthdate

Avatar of Scott Fell
Scott FellFlag for United States of America asked on
PHP
23 Comments1 Solution33 ViewsLast Modified:
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;




}


Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 23 Comments.
Join the Community
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.
Unlock 1 Answer and 23 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros