Suppose, we have a table users having id, name and date_of_birth as column name. So to display upcoming birthday and days left you need to execute the following query:
SELECT id, name, date_of_birth, DATE_FORMAT( NOW( ) , '%Y' ) - DATE_FORMAT( date_of_birth, '%Y' ) + IF( DATE_FORMAT( date_of_birth, '%m%d' ) < DATE_FORMAT( NOW( ) , '%m%d' ) , 1, 0 ) AS new_age, DATEDIFF( date_of_birth + INTERVAL YEAR( NOW( ) ) - YEAR( date_of_birth ) + IF( DATE_FORMAT( NOW( ) , '%m%d' ) > DATE_FORMAT( date_of_birth, '%m%d' ) , 1, 0 ) YEAR, NOW( ) ) AS days_to_dob
FROM `users`
HAVING days_to_dob < [number of days]
ORDER BY days_to_dob ASC;
In above number of days can be any numeric value according to your requirement. Suppose you want the birthday of the users within 90 days. So in this case query will be as follows:
SELECT id, name, date_of_birth, DATE_FORMAT( NOW( ) , '%Y' ) - DATE_FORMAT(date_of_birth , '%Y' ) + IF( DATE_FORMAT( date_of_birth, '%m%d' ) < DATE_FORMAT( NOW( ) , '%m%d' ) , 1, 0 ) AS new_age, DATEDIFF( date_of_birth + INTERVAL YEAR( NOW( ) ) - YEAR( date_of_birth ) + IF( DATE_FORMAT( NOW( ) , '%m%d' ) > DATE_FORMAT( date_of_birth, '%m%d' ) , 1, 0 ) YEAR, NOW( ) ) AS days_to_dob
FROM `users`
HAVING days_to_dob < 90
ORDER BY days_to_dob ASC;
0 Comment(s)