4

I have a model with field in datetime format, i want to filter the field with equal today date like this:

$collections = $this->customFactory->create()->getCollection()
      ->addFieldToFilter('created_at',date("Y-m-d"));
return $collections->getSize();

but it always return 0

1
  • Check my updated answer will help in your issue. Jul 3, 2018 at 10:43

3 Answers 3

9

You can use below code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objDate = $objectManager->create('Magento\Framework\Stdlib\DateTime\DateTime');
$now = $objDate->timestamp();
$start = date('Y-m-d' . ' 00:00:00', $now);
$end = date('Y-m-d' . ' 23:59:59', $now);
$collections = $this->customFactory->create()->getCollection();
$collections->addFieldToFilter('created_at', array('from' => $start, 'to' => $end));
return $collections->getSize();
4

Try this code:

$collections = $this->customFactory->create()->getCollection()
      ->addFieldToFilter('created_at', date("Y-m-d H:i:s"));
return $collections->getSize();
2

Solution:

$now = new \DateTime();
$collections = $this->customFactory->create()->getCollection()
      ->addFieldToFilter('created_at',$now->format('Y-m-d'));

return $collections->getSize();
1
  • this is not working Jul 3, 2018 at 11:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.