[PHP,MySQL]生年月日から年齢を算出する

生年月日から年齢を算出する

■PHP

$birth = '1952-01-26 00:00:00';
$age = (int) ((date('Ymd') - preg_replace('/([\- ]|[0-9]{2}:[0-9]{2}:[0-9]{2})/','',$birth)) / 10000);
echo $age;

結果

65

■MySQL

new_users

id name birth
1 1-名前 1941-01-26 17:30:56
2 2-名前 1952-07-07 00:30:56
3 3-名前 1976-09-02 17:30:56
4 4-名前 1990-05-13 05:00:00
5 5-名前 2016-11-26 17:30:56
6 6-名前 1999-04-01 11:11:11

SQL

SELECT
id,
name,
birth,
DATE_FORMAT(birth, '%Y%m%d') AS tmp_birth,
DATE_FORMAT(NOW(), '%Y%m%d') AS now_date,
FLOOR((DATE_FORMAT(NOW(), '%Y%m%d') - DATE_FORMAT(birth, '%Y%m%d')) / 10000) AS age
FROM new_users
ORDER BY id ASC

結果

id name birth tmp_birth now_date age
1 1-名前 1941-01-26 17:30:56 19410126 20170126 76
2 2-名前 1952-07-07 00:30:56 19520707 20170126 64
3 3-名前 1976-09-02 17:30:56 19760902 20170126 40
4 4-名前 1990-05-13 05:00:00 19900513 20170126 26
5 5-名前 2016-11-26 17:30:56 20161126 20170126 0
6 6-名前 1999-04-01 11:11:11 19990401 20170126 17