试着计算下一个生日的天数

时间:2011-12-04 18:26:14

标签: php mysql sql

我有这个脚本计算天,直到有人的下一个生日(这可能是一个更好的方式)但是无论如何,如果有人的生日是3天前,我希望它给我362天,直到下一个生日,但它给-3代替。没问题,添加365天以获得正确的答案,但它根本不起作用,我无法弄清楚为什么......代码:

$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); }

为什么这不起作用的任何想法?

有没有办法用SQL查询执行此操作?生日是日期字段类型。

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:1)

代码较少的替代项:

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

说明:
 1.以天为单位获取当前年龄:
TIMESTAMPDIFF(day, '1974-02-28', CURDATE())

 2.通过将当前年龄(天)除以365.25,可以得到自上次生日以来的天数,然后得出余数:
(TIMESTAMPDIFF(day, '1974-02-28', CURDATE()) mod 365.25)

 3.从365.25中减去余数,以查看到生日还剩下多少天:
365.25 - (TIMESTAMPDIFF(day, '1974-02-28', CURDATE()) mod 365.25)