gpt4 book ai didi

php - 获取日期范围内的用户生日

转载 作者:行者123 更新时间:2023-12-01 00:51:43 26 4
gpt4 key购买 nike

我想获取生日前后 3 天的用户列表。我的意思是,如果今天是 2013 年 3 月 2 日,我想获取生日从 2013 年 2 月 27 日2013 年 3 月 5 日。这是我的数据库设计。

用户表

id | name | birth_day | birth_month | birth_year

我无法再更改数据库设计,因为我无法访问它,并且更改设计只会发生在网站上的巨大变化上。

这是我当前的代码:

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

}

最佳答案

如果您不能更改表格设计,那么我会从三列中创建一个日期时间,然后将其用于过滤器:

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'

参见 SQL Fiddle with Demo .

这使用了 STR_TO_DATE()CONCAT()函数将生日创建为日期数据类型。确定日期后,您就可以应用日期过滤器。

关于php - 获取日期范围内的用户生日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15161817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com