Find age from a birthdate stored in any type of format php
<p>My client wants me to show a child's age using their birth date stored within mysql. My previous code didn't work for all formats, due to the site not limiting how the user can enter this date. Here is what I have so far, but I am having trouble figuring out how to check for the formats. They have birthdays in <code>mm/dd/yyyy</code>, <code>mm/dd/yy</code>, <code>dd/mm/yyyy</code>, <code>dd/mm/yy</code>, <code>Abbrev day, yy</code>, <code>Abbrev day, yyyy</code>. They also use different separators such as <code>.</code> or <code>-</code> which is easy enough to check for and use an explode.</p>

<pre><code>$birthday=//data from db
$DOB=$birthday;

if(strpos($DOB,'/')){
  list($month,$day,$year)=explode('/',$DOB);
  if(strlen($year)=='4'){
    //year is in Y format
    $age = (date("md", date("U", mktime(0, 0, 0, $month, $day, $year))) &gt; date("md") ? ((date("Y")-$year)-1):(date("Y")-$year));
  }else{
    if(strlen($month)=='4'){
      //format is adjusted using ymd - $month is actually the year, the $day is month, the $year is the day
      $age = (date("md", date("U", mktime(0, 0, 0, $day, $year, $month))) &gt; date("md") ? ((date("Y")-$month)-1):(date("Y") -$month));
    }else{
      //year is in y format
      $age = (date("md", date("U", mktime(0, 0, 0, $month, $day, $year))) &gt; date("md") ? ((date("y")-$year)-1):(date("y")-$year));
    }
  }
}elseif(strpos($DOB,'-')){
  list($month,$day,$year)=explode('-',$DOB);
  if(strlen($year)=='4'){
    //year is in Y format
    $age = (date("md", date("U", mktime(0, 0, 0, $month, $day, $year))) &gt; date("md") ? ((date("Y")-$year)-1):(date("Y")-$year));
  }else{
    if(strlen($month)=='4'){
      //format is adjusted using ymd - $month is actually the year, the $day is month, the $year is the day
      $age = (date("md", date("U", mktime(0, 0, 0, $day, $year, $month))) &gt; date("md") ? ((date("Y")-$month)-1):(date("Y") -$month));
    }else{
      //year is in y format
      $age = (date("md", date("U", mktime(0, 0, 0, $month, $day, $year))) &gt; date("md") ? ((date("y")-$year)-1):(date("y")- $year));
    }
  }
}elseif(strpos($DOB,'.')){
  list($month,$day,$year)=explode('.',$DOB);
  if(strlen($year)=='4'){
    //year is in Y format
    $age = (date("md", date("U", mktime(0, 0, 0, $month, $day, $year))) &gt; date("md") ? ((date("Y")-$year)-1):(date("Y")-$year));
  }else{
    if(strlen($month)=='4'){
      //format is adjusted using ymd - $month is actually the year, the $day is month, the $year is the day
      $age = (date("md", date("U", mktime(0, 0, 0, $day, $year, $month))) &gt; date("md") ? ((date("Y")-$month)-1):(date("Y") -$month));
    }else{
      //year is in y format
      $age = (date("md", date("U", mktime(0, 0, 0, $month, $day, $year))) &gt; date("md") ? ((date("y")-$year)-1):(date("y")- $year));
    }
  }
}else{}

echo $age;

}
</code></pre>
