Getting the current age in years:
SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(DATE(NOW()), birthday)), '%Y') * 1 AS age FROM table_name;
How this works:
- datediff(date1, date2) gives the difference between two dates in days. Note that the date format of 'birthday' here is date: YYYY-MM-DD.
- from_days converts days into a date format
- date_format function extracts with '%Y' only the four digit year. Don't use '%y', because you only get a two digit year and some people are older then 99 years.
- multiply the string with 1. This is a 'hack'. MySQL will convert a string like 'YYYY' into an integer.
Getting the current age in month (unlikley, but someone may need this)
SELECT (DATE_FORMAT(FROM_DAYS(DATEDIFF(DATE(NOW()), birthday)), '%Y') * 1 * 12)
+ (DATE_FORMAT(FROM_DAYS(DATEDIFF(DATE(NOW()), birthday)), '%m') * 1) AS age_in_months
FROM table_name;
How this works:
- Mostly the same as age in years above.
- The years get muliplied by 12. A (earth) year has 12 months.
- In the next step the months are extracted the same way as the years, but instead the flag '%Y' must be changed to '%m'.
- At the end the two values are added together.
Getting the current age in days is as simple as this:
SELECT DATEDIFF(DATE(NOW()), birthday) AS age_in_days FROM table_name;
Alternative code:
SELECT
DATE_FORMAT(age_date, '%Y') * 1 AS age_in_years,
(DATE_FORMAT(age_date, '%Y') * 1 * 12) + (DATE_FORMAT(age_date, '%m') * 1) AS age_in_months,
age_in_days
FROM
(SELECT
FROM_DAYS(DATEDIFF(DATE(NOW()), birthday)) AS age_date,
DATEDIFF(DATE(NOW()), birthday) AS age_in_days
FROM table_name) AS age_date;