4

How to load new product collection in magento 2 like we did in magento 1.x something like

->addAttributeToFilter('news_from_date', array('date' => true, 'to' => $todayDate))
1
  • You can check this answer its working well you can Check here
    – Waqar Ali
    Commented May 8, 2019 at 9:56

2 Answers 2

11

You can try this :

public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
    \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory $productCollectionFactory,
    array $data = []
    ) {

    $this->_productCollectionFactory = $productCollectionFactory;
    parent::__construct($context, $data);
}

public function getProductCollection()
{       
    $collection = $this->_productCollectionFactory->create();
    $todayDate  = date('Y-m-d', time());
    $collection->addAttributeToFilter('news_from_date', array('date' => true, 'to' => $todayDate));

    return $collection;
}
1
  • You can always accept the answer if it helped so as it serves a point of reference for others too.! Commented Jan 4, 2016 at 5:19
8

As you want to get a product collection then you need to get first current data start & end time.

So you can try below

$todayStartOfDayDate = $this->_localeDate->date()->setTime(0, 0, 0)->format('Y-m-d H:i:s');
$todayEndOfDayDate = $this->_localeDate->date()->setTime(23, 59, 59)->format('Y-m-d H:i:s');

Then using news_from_date and news_to_date fields ,you need to filter collection current data start and end time with date format (Y-m-d H:i:s);

Collection filter should be like this:

   $collection->addStoreFilter()->addAttributeToFilter(
            'news_from_date',
            [
                'or' => [
                    0 => ['date' => true, 'to' => $todayEndOfDayDate],
                    1 => ['is' => new \Zend_Db_Expr('null')],
                ]
            ],
            'left'
        )->addAttributeToFilter(
            'news_to_date',
            [
                'or' => [
                    0 => ['date' => true, 'from' => $todayStartOfDayDate],
                    1 => ['is' => new \Zend_Db_Expr('null')],
                ]
            ],
            'left'
        )->addAttributeToFilter(
            [
                ['attribute' => 'news_from_date', 'is' => new \Zend_Db_Expr('not null')],
                ['attribute' => 'news_to_date', 'is' => new \Zend_Db_Expr('not null')],
            ]
        )

See More at class Magento\Catalog\Block\Product\New Block at Magento2.

You Can use this block for ur purpose

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.