DetermineAgePHPFunction

From FreeBert Wiki

Jump to: navigation, search

Contents

[edit] Determine Age In Years Given Date Of Birth PHP Function - Support

This is the official support page for The freebert.com Free Determine Age In Years Given Date Of Birth PHP Function. Clink on the link for a full description, code listing and example for The freebert.com Free Determine Age In Years Given Date Of Birth PHP Function.

[edit] Full Example

To fully illustrate how to use this function, see the code below. The code is complete, and can be copied and pasted into a PHP page and opened to see it work in action:


    <?php
    
    // Example Age Input
    $DateOfBirth=19770226;
    
    // Calculate Age Using Function:
    $Age= DetermineAgeFromDOB ($DateOfBirth);
    
    // Display Results
    echo "A person born on ".$DateOfBirth." is now ".$Age." years old.";
    
    // Define the function
    function DetermineAgeFromDOB ($YYYYMMDD_In)
    {
      // Parse Birthday Input Into Local Variables
      // Assumes Input In Form: YYYYMMDD
      $yIn=substr($YYYYMMDD_In, 0, 4);
      $mIn=substr($YYYYMMDD_In, 4, 2);
      $dIn=substr($YYYYMMDD_In, 6, 2);
    
      // Calculate Differences Between Birthday And Now
      // By Subtracting Birthday From Current Date
      $ddiff = date("d") - $dIn;
      $mdiff = date("m") - $mIn;
      $ydiff = date("Y") - $yIn;
    
      // Check If Birthday Month Has Been Reached
      if ($mdiff < 0) 
      {
        // Birthday Month Not Reached
        // Subtract 1 Year From Age
        $ydiff--;
      } elseif ($mdiff==0)
      {
        // Birthday Month Currently
        // Check If BirthdayDay Passed
        if ($ddiff < 0)
        {
          //Birthday Not Reached
          // Subtract 1 Year From Age
          $ydiff--;
        }
      }
      return $ydiff; 
    } 
    ?>

[edit] Questions & Feedback

Post any questions, issues, problems, and comments you may have regarding this function below.


[edit] Posted June 16 2008

The script works fine as is. But how would I go about writing a script that prompts a user for their birthday so that it is assigned to the .$DateOfBirth variable? This way a user could type in their birthday and the script would calculate their age.

Thanks. Art

---> Response: Use an HTML form (POST or GET), use 1 drop down box each for day, month, and year. Upon form submission, take the submitted values (POST or GET), put them into 1 string using format YYYYMMDD. Plug that into the function as in the example above and place the output in user friendly text based output (also as in the example above). For more info, lookup using POST and GET with PHP here.

Personal tools
Toolbox