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

标签 php mysql cakephp

我想获取生日前后 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/

相关文章:

php - 在没有网络服务器的情况下在 linux 上使用 php 从文件夹发送电子邮件

php - 用于搜索器的两个非关系表的 SQL 语句

PHP MySQL 转储脚本帮助

mysql - 带有多个where语句的sql查询

PHP、MySQL 错误 : Column count doesn't match value count at row 1

PHP ImageMagick - readimage 不适用于某些 pdf

php - 使用PHP的GDlib imagecopyresampled时可以保留PNG图像透明度吗?

cakephp - Mootools 1.3.2 Request.HTML 获取表行

php - cakePHP 文件下载未找到或不可读

php - CakePHP:加入操作不起作用