我想获得今天之前和之后3天生日的用户列表.我的意思是,如果今天是March 2,2013,我想谁也开始过生日的用户Feb 27,2013高达March 5,2013.这是我的数据库设计.
用户表
id | name | birth_day | birth_month | birth_year
Run Code Online (Sandbox Code Playgroud)
我无法再更改数据库设计,因为我无法访问它,更改设计只会发生在网站上的巨大变化.
这是我目前的代码:
if (empty($date))
$date = date('Y-m-d'); // now
$start_date = strtotime($date.' -'.$day_range.' day');
$end_date = strtotime($date.' +'.$day_range.' day');
$start_month = date('m', $start_date);
$end_month = date('m', $end_date);
$start_day = date('d', $start_date);
$end_day = date('d', $end_date);
if ($start_day > $end_day) {
$tmp = $start_day;
$start_day = $end_day;
$end_day = $tmp;
}
/* This is a dirty fix for getting birthdays between dates */
$this->User->contain(array('User' => array('first_name', 'last_name', 'userstatus_id')));
$user = $this->User->find('all', array(
'conditions' => array(
'User.birth_month BETWEEN ? AND ?' => array($start_month, $end_month),
'User.birth_day BETWEEN ? AND ?' => array($start_day, $end_day),
),
'fields' => array(
'birth_year',
'birth_day',
'birth_month'
),
'order' => array(
'birth_month' => 'ASC',
'birth_day' => 'ASC'
)
));
foreach($user as $k => $v) {
$temp = strtotime(date('Y-'.$user[$k]['User']['birth_month'].'-'.$user[$k]['User']['birth_day']));
if ($temp >= $start_date && $temp <= $end_date) {
}
else {
unset($user[$k]);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您无法更改表格设计,那么我将从三列创建日期时间,然后将其用于过滤器:
select *
from
(
select id, name,
str_to_date(concat(year(now()), '-', birth_month, '-', birth_day), '%Y-%m-%d') birthdate
from users
) d
where birthdate >= '2013-02-27'
and birthdate <= '2013-03-05'
Run Code Online (Sandbox Code Playgroud)
这使用STR_TO_DATE()和CONCAT()函数创建生日日期作为日期数据类型.获得日期后,您就可以应用日期过滤器了.