Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP calculate age

Tags:

php

People also ask

How to Calculate age of a person in PHP?

php $bday = new DateTime('11.4. 1987'); // Your date of birth $today = new Datetime(date('m.d.y')); $diff = $today->diff($bday); printf(' Your age : %d years, %d month, %d days', $diff->y, $diff->m, $diff->d); printf("\n"); ?>

How to get age from birthday in PHP?

$diff = date_diff(date_create($dateOfBirth), date_create($today)); echo 'Age is '. $diff->format('%y'); Use the above code to get the age from date of birth using PHP date functions.

How do I calculate age in MySQL?

Calculate Age based on date of birth with the help of DATE_FORMAT() method in MySQL. Firstly, get the current date time with the help of now() method and you can place your date of birth in DATE_FORMAT().

How do I calculate age in HTML?

function calculateAge(date) { const now = new Date(); const diff = Math. abs(now - date ); const age = Math. floor(diff / (1000 * 60 * 60 * 24 * 365)); return age } var picker = new Pikaday({ field: document.


This works fine.

<?php
  //date in mm/dd/yyyy format; or it can be in other formats as well
  $birthDate = "12/17/1983";
  //explode the date to get month, day and year
  $birthDate = explode("/", $birthDate);
  //get age from date or birthdate
  $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
    ? ((date("Y") - $birthDate[2]) - 1)
    : (date("Y") - $birthDate[2]));
  echo "Age is:" . $age;
?>

$tz  = new DateTimeZone('Europe/Brussels');
$age = DateTime::createFromFormat('d/m/Y', '12/02/1973', $tz)
     ->diff(new DateTime('now', $tz))
     ->y;

As of PHP 5.3.0 you can use the handy DateTime::createFromFormat to ensure that your date does not get mistaken for m/d/Y format and the DateInterval class (via DateTime::diff) to get the number of years between now and the target date.


 $date = new DateTime($bithdayDate);
 $now = new DateTime();
 $interval = $now->diff($date);
 return $interval->y;

I use Date/Time for this:

$age = date_diff(date_create($bdate), date_create('now'))->y;

Simple method for calculating Age from dob:

$_age = floor((time() - strtotime('1986-09-16')) / 31556926);

31556926 is the number of seconds in a year.


// Age Calculator

function getAge($dob,$condate){ 
    $birthdate = new DateTime(date("Y-m-d",  strtotime(implode('-', array_reverse(explode('/', $dob))))));
    $today= new DateTime(date("Y-m-d",  strtotime(implode('-', array_reverse(explode('/', $condate))))));           
    $age = $birthdate->diff($today)->y;

    return $age;
}

$dob='06/06/1996'; //date of Birth
$condate='07/02/16'; //Certain fix Date of Age 
echo getAge($dob,$condate);