Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save suttipong-srikok/8f1b54fe718a367cb214 to your computer and use it in GitHub Desktop.
Save suttipong-srikok/8f1b54fe718a367cb214 to your computer and use it in GitHub Desktop.

Calculate age form date of birth (timestamp).

public function calculate_age($dob_timestamp) {
    if (version_compare(PHP_VERSION, '5.3.0') >= 0):
        $birth_time = date("Y-m-d", $dob_timestamp);
        $from = new DateTime($birth_time);
        $to = new DateTime('today');
        return $from->diff($to)->y;
    else:
        return $this->structured_method($birthDate);
    endif;
}
    
public function structured_method($dob_timestamp) {
    $birth_time = date("m/d/Y", $dob_timestamp);
    //explode the date to get month, day and year
    $birthDate = explode("/", $birth_time);
    $unix_time = mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]);
    $first_date = date("md", date("U", $unix_time);
    $second_date =  date("md");
    if ( $first_date > $second_date ):
        return (date("Y") - $birthDate[2]) - 1;
    else:
        return date("Y") - $birthDate[2]);
    endif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment