简体   繁体   中英

How to convert a date of birth into an age and save it into a table?

I am creating a online record for our family members.

I have two tables Member and MemberDetails, and the BirthDate is inserted in the 'member' table. I want to calculate age using this BirthDate stored in table 'Member' and store it in table MemberDetails for each member under the column 'Age'.

You can do this directly in SQL,

Try something like

INSERT INTO Member_Detail (id, dob)
VALUES SELECT id, TIMESTAMPDIFF(YEAR, dob, CURDATE()) FROM Member

Try this -

<?php
$birthDate = "05-03-1991";  // m-d-Y
$birthDate = explode("-", $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 "Your age is:" . $age;

Example:-

<?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;
?>

or refer this link PHP calculate age

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM