Magento – Get product collection filter by from and to date in magento2.

magento2

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()
        ->addAttributeToSelect('*')
        ->load();

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?

Best Answer

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')
        ->getData();