如何比较Doctrine2的日期时间字段和日期?

时间:2012-05-21 07:37:46

标签: datetime symfony doctrine-orm

我想从Doctrine2获取由QueryBuilder创建的项目。我想将createdAt(Datetime)字段与今天参数(Date)进行比较。是否可以在一个查询中执行此操作?

$qb = $this->createQueryBuilder('i');
$qb->innerJoin('i.type', 'it');
$qb->andWhere('it.name = :type');
$qb->andWhere('i.createdAt < :today');
// i.createdAt == datetime and :today parameter is a date

6 个答案:

答案 0 :(得分:21)

一个想法是从日期中提取:年,月和日。然后

$qb->select('p')
   ->where('YEAR(p.postDate) = :year')
   ->andWhere('MONTH(p.postDate) = :month')
   ->andWhere('DAY(p.postDate) = :day');

$qb->setParameter('year', $year)
   ->setParameter('month', $month)
   ->setParameter('day', $day);

MONTH DAY,以及从

中取出DoctrineExtensions的年份

e.g。

DoctrineExtensions

这对我有用。你只需要文件:day.php,month.php和year.php .....

你得到月份,例如:

    $datetime = new \DateTime("now");
    $month = $datetime->format('m');
    echo $month;

将day.php,month.php和year.php复制到您的捆绑包Xy \ TestBundle \ Dql 使用

在app \ config.yml中注册新功能
doctrine:


orm:
    auto_generate_proxy_classes: %kernel.debug%
    entity_managers:
        default:
            auto_mapping: true
            dql:
                datetime_functions:
                    month: Xy\TestBundle\Dql\Month
                    year: Xy\TestBundle\Dql\Year
                    day: Xy\TestBundle\Dql\Day

答案 1 :(得分:14)

比添加日期的学说扩展名更好。

首先,你需要获得start-datetime和end-datetime:

$today_startdatetime = \DateTime::createFromFormat( "Y-m-d H:i:s", date("Y-m-d 00:00:00") );
$today_enddatetime = \DateTime::createFromFormat( "Y-m-d H:i:s", date("Y-m-d 23:59:59") );

现在在查询中使用它们:

$em = \Zend_Registry::get('em');
$qb_1 = $em->createQueryBuilder();
$q_1 = $qb_1->select('wsh')
    ->from('\Entities\wishes', 'wsh')
    ->where('wsh.created_at >= :today_startdatetime')
    ->andWhere('wsh.created_at <= :today_enddatetime');


$q_1->setParameter('today_startdatetime', $today_startdatetime);
$q_1->setParameter('today_enddatetime', $today_enddatetime);
$result= $q_1->getQuery ()->getResult ();

答案 2 :(得分:13)

这种成熟的ORM很少提供DATE功能。但是,要从日期时间字段中获取日期,您可以像这样应用SUBSTRING函数:

SELECT SUBSTRING(i.dateTimeField,1,10) FROM tableName i

希望它有所帮助!

答案 3 :(得分:12)

也可以使用内置函数DATE_DIFF(date1, date2)来返回天数差异。查看docs

$result = $this->createQueryBuilder('l')
    ->where('DATE_DIFF(l.startDate, CURRENT_DATE()) = 0')

答案 4 :(得分:5)

您必须向查询QueryBuilder添加today参数。

$today = new \DateTime();
$qb->setParameter('today', $today->format('Y-m-d'));

使用QueryBuilder,您可以将日期与DateTime进行比较,格式为'Y-m-d'

答案 5 :(得分:3)

An easy solution would be to format the datetime accordingly

public function getWithStartingPremium(\DateTime $datetime)
{
    $qb = $this->createQueryBuilder('c');

    return $qb
        ->innerJoin('c.collegePremium', 'cp')
        ->where($qb->expr()->eq('cp.start', ':date'))
        ->setParameters(array(
            'date' => $datetime->format('Y-m-d'),
        ))
        ->getQuery()
        ->getResult();
}