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?

2 Answers 2


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, 2016 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, 2016 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, 2016 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, 2016 at 4:43
  • Why do you inject \Magento\Framework\Stdlib\DateTime\DateTime if you don't use it in your code?
    – jrswgtr
    May 24, 2019 at 13:48
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

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

$startDate = date("Y-m-d h:i:s",strtotime('2023-09-1')); // start range
 $endDate = date("Y-m-d h:i:s", strtotime('2023-10-1')); // end range

$collection = $productCollection->create()->addAttributeToSelect('*')
 ->addAttributeToFilter('from_date', array('gteq',$startDate)); //Date attribute filter
 ->addAttributeToFilter('to_date', array('lteq',$endDate)); //Date attribute filter

if($collection->getSize() > 0){
    foreach ($collection as $product){
        //enter code here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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