Welcome to Kodok Marton's homepage

Professional work from professionals!

  • Increase font size
  • Default font size
  • Decrease font size
Home Programming Web Programming How to properly get user's birthday from database (solution for 29th February)

How to properly get user's birthday from database (solution for 29th February)

Today, I came across a problem, where I had to get from database all users that celebrate today. This is not as easy as it sounds, as there are leap years, and users having their birthday on 29th February will be returned only in 4 years. It's better return them on 1st March if the 29th February doesn't exists in that year. Actually, if you need to be serious about this, you have to take into account, that every 100 years, there's no leap year, but every 400 there is. 

Here is an answer that property takes into account leap-years and will always give you the users whose birthday is on the 29th of February at the same time as those on the 1st of March.

SELECT * 
  FROM USERS
  WHERE
     DATE_FORMAT
(FROM_UNIXTIME(birthDate),'%m-%d') = DATE_FORMAT(NOW(),'%m-%d')
     OR
(
           
(
                DATE_FORMAT
(NOW(),'%Y') % 4 <> 0
                OR
(
                        DATE_FORMAT
(NOW(),'%Y') % 100 = 0
                        AND DATE_FORMAT
(NOW(),'%Y') % 400 <> 0
                   
)
           
)
            AND DATE_FORMAT
(NOW(),'%m-%d') = '03-01'
            AND DATE_FORMAT
(FROM_UNIXTIME(birthDate),'%m-%d') = '02-29'
       
)

 

Tags: