I want to get product collection filter by From date and to date. How can I get this?

I have used below code in my phtml file so I get all product collection.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

$collection = $productCollection->create()

foreach ($collection as $product){
//echo 'Name  =  '.$product->getName().'<br>';

Right now I have used addAttributeToSelect('*') so I am getting all product collection but I want to filter these collection by from date and to date.

How can I get that?


Inject class \Magento\Framework\Stdlib\DateTime\DateTime $stdlibDateTime
For example your collection have field from_date and to_date

    // init current time now
    $currentTime = $this->stdlibDateTime->date();

    // Filter datetime
    $collections = $this->getResourceCollection()
        ->addFieldToFilter('from_date', ['lteq' => $currentTime])
        ->addFieldToFilter('to_date', ['gteq' => $currentTime])
        ->setOrder('sort_order', 'ASC')
  • I want to get product's special price's from and to date how can I do it? – Dhaval Jul 7 '16 at 10:41
  • how can I inject \Magento\Framework\Stdlib\DateTime\Timezone $_stdTimezone and \Magento\Framework\Stdlib\DateTime\DateTime $stdlibDateTime in phtml file? – Dhaval Jul 7 '16 at 10:47
  • You can inject all those classes in your Block Class or Models and call collection into templates by $block->getCollection() for example – mrtuvn Jul 7 '16 at 17:51
  • if you know how to get from and to date filter in collection then please write code here. I don't think you code work. – Dhaval Jul 8 '16 at 4:43
  • Why do you inject \Magento\Framework\Stdlib\DateTime\DateTime if you don't use it in your code? – jrswgtr May 24 '19 at 13:48

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.