StudioTime
StudioTime

Reputation: 23989

Trying to calculate days to next birthday

I have this script which calculates days until someone's next birthday (there's probably a better way of doing this) but anyway, if someone's birthday was 3 days ago I want it to give me 362 days until next birthday but it gives -3 instead. No problem, add 365 days to that to get correct answer but it simply doesn't work and I can't work out why...the code:

$resultcurdate = mysql_query("select curdate()",$db);

    $curdate = mysql_fetch_array($resultcurdate);

    $curdate1 = explode('-', $curdate[0]);
    $day1   = $curdate1[2];
    $month1 = $curdate1[1];
    $year1  = $curdate1[0];

    $birthdate = explode('-', $databack10[birthday]);
    $day   = $birthdate[2];
    $month = $birthdate[1];
    $year  = $birthdate[0];

    $year = $year1;

    if ($month1>$month){$year=$year+1;}

    $birthdate5 = $year."-".$month."-".$day;

    $resultdate = mysql_query("select datediff('$birthdate5', now())",$db);

    $databackdate = mysql_fetch_array($resultdate);

    if($databackdate < '0'){$databackdate = (365 + $databackdate); }

Any ideas why this doesn't work?

Is there a way to do this with a SQL query? Birthday is date fieldtype.

Upvotes: 2

Views: 3211

Answers (2)

Phil
Phil

Reputation: 774

An alternate which has a bit less code:

select 365.25 - ( TIMESTAMPDIFF(day, '1974-02-28', CURDATE()) mod 365.25 ) AS days_till_birthday

Explanation:
1. Get the current age in days:
TIMESTAMPDIFF(day, '1974-02-28', CURDATE())

2. Get how many days since the last birthday by dividing the current age in days by 365.25 and get the remainder:
(TIMESTAMPDIFF(day, '1974-02-28', CURDATE()) mod 365.25)

3. Subtract the remainder from 365.25 to see how many days left until the birthday:
365.25 - (TIMESTAMPDIFF(day, '1974-02-28', CURDATE()) mod 365.25)

Upvotes: 2

Nicola Cossu
Nicola Cossu

Reputation: 56357

select 
date_field,
abs(if(right(curdate(),5) >= right(date_field,5),
datediff(curdate(),concat(year(curdate()+ interval 1 year),right(date_field,6))) ,
datediff(concat(year(curdate()),right(date_field,6)),curdate()))) as days
from table

Upvotes: 7

Related Questions