mysql birthday reminder, leap year

Posted by moodh on Stack Overflow See other posts from Stack Overflow or by moodh
Published on 2010-02-08T19:49:30Z Indexed on 2010/05/04 0:58 UTC
Read the original article Hit count: 340

Filed under:
|

Hi, I'm trying to sort out a result set that gives the 5 closest users sorted by upcoming birthday. This works perfectly until leap years comes into play. For example:

  • May 15th - 96 days left
  • May 15th - 97 days left

The top result is a birth at 1987 and the lower is from 1988. u_birth is stored as yyyy-mm-dd. Is there a simple way to sort this problem without having to rewrite the entire query?

SELECT u_birth, IF( DAYOFYEAR( u_birth ) >= DAYOFYEAR( NOW() ), 
          DAYOFYEAR( u_birth ) - DAYOFYEAR( NOW() ), 
          DAYOFYEAR( u_birth ) - DAYOFYEAR( NOW() ) +  
      DAYOFYEAR( CONCAT( YEAR( NOW() ), '-12-31' ) ) 
 )  
 AS distance
FROM (blog_users)
WHERE `s_agehide` = 0
ORDER BY distance ASC
LIMIT 5

This query is taken and modified from the mysql manual: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#c7489

© Stack Overflow or respective owner

Related posts about mysql

Related posts about leap-year