Magento 2 Orders – How to Get Orders from the Last 2 Days

magento2orderssales-order

I need to get the orders collection from the last 2 Days until now (including today).

Example: If today is 11/30/2017 -> then I need orders from 11/28/2017, 11/29/2017 and 11/30/2017.

This is how I started:

    public function __construct(

    \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
    \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
    \Magento\Framework\Api\SortOrderBuilder $sortBuilder,
    \Magento\Framework\View\Element\Template\Context $context,
    array $data = [])
    {

      $this->orderRepository = $orderRepository;
      $this->searchCriteriaBuilder = $searchCriteriaBuilder;
      $this->sortBuilder = $sortBuilder;

      parent::__construct($context, $data);
    }

    protected function _prepareLayout()
    {
          $searchCriteria = $this->searchCriteriaBuilder
          ->addFilter('status','pending','eq')
          ->addSortOrder($this->sortBuilder->setField('entity_id')
          ->setDescendingDirection()->create())
          ->setPageSize(100)->setCurrentPage(1)->create();

          $ordersList = $this->orderRepository->getList($searchCriteria);
    }

When I print out an order from the $ordersList, this is what I get:

{"entity_id":"21","state":"new","status":"pending","coupon_code":null,"protect_code":"619c73", ….
,"created_at":"2017-11-23 10:15:18","updated_at":"2017-11-24 16:03:37", …. }

So I think filtering by 'created_at' field is probably the solution.

Maybe something like: ->addFilter('created_at','<today minus 2 days>','gteq')

Any tips on how to do that correctly ?

Thanks

Best Answer

Try below code

protected function _prepareLayout()
{
    $searchCriteria = $this->searchCriteriaBuilder
      ->addFilter('status','pending','eq')
      ->addSortOrder($this->sortBuilder->setField('entity_id')
      ->setDescendingDirection()->create())
      ->setPageSize(100)->setCurrentPage(1)->create();

    $to = date("Y-m-d h:i:s"); // current date
    $from = strtotime('-2 day', strtotime($to));
    $from = date('Y-m-d h:i:s', $from); // 2 days before

    $ordersList = $this->orderRepository->getList($searchCriteria);
    $ordersList->addFieldToFilter('created_at', array('from'=>$from, 'to'=>$to));
}
Related Topic