简体   繁体   中英

Get dates in doctrine query builder

Good day,

I'm trying to get the dates 'older than 2 months from now' and 'younger than six months from now' in my doctrine query builder.

What I currently have is;

if ($type == 'older_than_two_months') {
    $qb->andWhere('i.createdAt < ');
}
if ($type == 'younger_than_six_months') {
    $qb->andWhere('i.createdAt > ');
}

$qb->orderBy('i.createdAt', 'DESC')
    ->setParameter('status', $status);

Do I just have to add an extra parameter? But I don't know how to get the date of a few months ago.

Actually very simple with the PHP DateTime's:

if ($type == 'older_than_two_months') {
    $qb->andWhere('i.createdAt < :olderThan')
        ->setParameter('olderThan', new \DateTime('-2 months'));
}
if ($type == 'younger_than_six_months') {
    $qb->andWhere('i.createdAt > :youngerThan')
        ->setParameter('olderThan', new \DateTime('-6 months'));
}
if ($type == 'older_than_two_months') {
    $qb->andWhere('f.dateAdded < :twoMonthsAgo')
    $qb->setParameter(':twoMonthsAgo', (new \DateTime())->modify('-2months'))
}
if ($type == 'younger_than_six_months') {
    $qb->andWhere('f.dateAdded > :sixMonthsAgo')
    $qb->setParameter(':sixMonthsAgo', (new \DateTime())->modify('-6months'))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM