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();
The authentic and recommended way to fetch product collection is to use API interface
Magento\Catalog\Api\ProductRepositoryInterface
method
getList(\Magento\Framework\Api\SearchCriteriaInterface
$searchCriteria)
for this you need to build the search criteria first
Your class should include below classes -
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
Class constructor should be -
/** @var ProductRepositoryInterface */
protected $productRepository;
/** @var SearchCriteriaBuilder */
protected $searchCriteriaBuilder;
/** @var Visibility */
protected $productVisibility;
/** @var Status */
protected $productStatus;
/**
* Edit constructor.
* @param ProductRepositoryInterface $productRepositoryInterface
* @param SearchCriteriaBuilder $searchCriteriaBuilder
* @param Visibility $visibility
* @param Status $status
*/
public function __construct(
ProductRepositoryInterface $productRepositoryInterface,
SearchCriteriaBuilder $searchCriteriaBuilder,
Visibility $visibility,
Status $status
) {
$this->productRepository = $productRepositoryInterface;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->productVisibility = $visibility;
$this->productStatus = $status;
}
Get list method should be -
/**
* @return array
*/
public function getProductList()
{
$searchCriteriaBuilder = $this->searchCriteriaBuilder
->addFilter('type_id', Type::TYPE_SIMPLE, 'eq')
->addFilter('status', $this->productStatus->getVisibleStatusIds(), 'in')
->addFilter('visibility', $this->productVisibility->getVisibleInCatalogIds(), 'in')
->create();
$productList = $this->productRepository->getList($searchCriteriaBuilder);
//echo $productList->getTotalCount();
$items = $productList->getItems();
return $items;
}
Best Answer
You can try the below code in your root file.