Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MYSQL: Get Upcoming Birthdays Year End Issue

Currently, I have a MySQL query to return upcoming birthdays from the current date to the next 7 days, and it is working fine, but since it’s the end of the year I have issues getting results.

The main issue is after December 25th it checks birthdays between 12-26 and 01-02 due to the end of the year. Below is my code


SELECT u.id, u.birthday FROM users as u
WHERE DATE_FORMAT(u.birthday, '%m-%d') >= DATE_FORMAT(NOW(), '%m-%d') and DATE_FORMAT(u.birthday, '%m-%d') <= DATE_FORMAT((NOW() + INTERVAL +7 DAY), '%m-%d');

Can someone help me to update this query to get results?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to add the year-to-date format but it doesn’t give expected results.

>Solution :

You need to check if the year in a week is different from the current year, and use a different condition. The condition then should be OR rather than AND.

WHERE CASE WHEN YEAR(NOW()) = YEAR(NOW() + INTERVAL 7 DAY)
        THEN DATE_FORMAT(u.birthday, '%m-%d') BETWEEN DATE_FORMAT(NOW(), '%m-%d') AND DATE_FORMAT((NOW() + INTERVAL +7 DAY), '%m-%d')
        ELSE DATE_FORMAT(u.birthday, '%m-%d') >= DATE_FORMAT(NOW(), '%m-%d') OR DATE_FORMAT(u.birthday, '%m-%d') <= DATE_FORMAT((NOW() + INTERVAL +7 DAY), '%m-%d')
    END
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading