3

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

  • Check my updated answer will help in your issue. – Nikunj Vadariya Jul 3 '18 at 10:43
5

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();
2

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();
  • this is not working – Tiny Dancer Jul 3 '18 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.