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))
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;
}
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